Updating stubs after mockito null-safety upgrade:
To outline the process, a stubbed class will need to be generated, which is done using build_runner
package. You will need to import that class and stub required methods.
- Update the class - remove 'Mock' from the stub definition, because the imported stub class will start with 'Mock', eg:
class MyClass extends Mock implements MyClassBase {}
instead of
class MockMyClass extends Mock implements MyClassBase {}
- Before main add
@GenerateMocks([MockedClass])
eg @GenerateMocks([MyClass])
(it'll require an import: import 'package:mockito/annotations.dart';
)
- Install build_runner
- Generate stub class by running
flutter pub run build_runner build --delete-conflicting-outputs
- Import the stubbed class in your test file, which will be generated in the same directory as your test file, import will look like
import '{TEST_FILE_NAME}.mocks.dart';
. Now the stub class is available with the same name as given in Generate(
starting with Mock
, eg MockMyClass
- Stub required method, before the call/assertion (provide parameters and return value):
when(mockMyClass.someFancyMethod(any, any))
.thenAnswer((_) => Future.value(null));
PS
Was having issues mocking NavigatorObserver this way, the error I got:
The following MissingStubError was thrown building IconTheme(color: Color(0xdd000000)): 'navigator'
Stubbing navigator
with NavigatorState
didn't help, I guess it's related to context propagation.
I worked around it by using the following non-null safe way, as specified in mockito's null-safety guideline:
@GenerateMocks([],
customMocks: [
MockSpec<NavigatorObserver>(returnNullOnMissingStub: true)
])
after that run
flutter pub run build_runner build --delete-conflicting-outputs
It'll yield MockNavigatorObserver
available through the import of *.mocks.dart
file (mentioned above). Of course, since it's generated by mockito need to remove any custom definitions of that class.