unit-testingdartflutter

Unit testing in Flutter passing BuildContext


I have a method in a Dart class, which accepts BuildContext parameter, as follows:

class MyClass {

  <return_type> myMethodName(BuildContext context, ...) {
        ...
        doSomething
        return something;
    }
}

I want to test that the method works as expected:

import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
...

void main() {
  MyClass sut;

  setUp(() {
    sut = MyClass();
  });

  test('me testing', () {

    var actual = sut.myMethodName(...);        

    expect(actual, something);
  });
}

Of course, it won't work, because the method myMethodName needs a parameter BuildContext type. This value is available throughout the application itself, but not sure where to get that from in my unit tests.


Solution

  • You can actually mock the BuildContext so the test will run headless. I think it's better but might be not a solution that you are looking for.

    BuildContext is an abstract class therefore it cannot be instantiated. Any abstract class can be mocked by creating implementations of that class. If I take your example then the code will look like this:

    class MockBuildContext extends Mock implements BuildContext {}
    
    void main() {
       MyClass sut;
       MockBuildContext _mockContext;
    
       setUp(() {
         sut = MyClass();
         _mockContext = MockBuildContext();
       });
    
       test('me testing', () {
    
       var actual = sut.myMethodName(_mockContext, ...);        
    
       expect(actual, something);
      });
    }
    

    (Note that this requires the Mockito package: https://pub.dev/packages/mockito).