So I am writing widget testing for Flutter using flutter test plugin. So, in my test widget, I am using mockito to mock third party services. So, I am getting an error that says 'type Null is not a subtype of bool'. I tried to cover for that but I do not get why am I still getting the error when I run the test code.
I tried to cover for that but I do not get why am I still getting the error when I run the test code. Here is my code below:
class MockGlobalSearchViewModel extends Mock implements GlobalSearchViewModel {}
@GenerateMocks([MockGlobalSearchViewModel])
testWidgets('Global Widget Test', (WidgetTester tester) async {
// Create mock instances
final mockGlobalSearchViewModel = MockGlobalSearchViewModel();
when(mockGlobalSearchViewModel.isNetworkError()).thenReturn(true);//this is where I am getting the error
final globalSearchViewModelProvider = Provider<GlobalSearchViewModel>.value(value: mockGlobalSearchViewModel);
await tester.pumpWidget(
MaterialApp(
home: MultiProvider(
providers: [
globalSearchViewModelProvider,
],
child: const GlobalSearchWidget()
So, can I please have some assistance from anyone, I honestly tried anything and I cannot get why am I not getting it right.
You're getting the error because the mocks for GlobalSearchViewModel
has not been generated. Mockito uses code generation to create its mocks.
To generate the mocks for GlobalSearchViewModel
, do the following:
Remove the manually written mock from your test file:
class MockGlobalSearchViewModel extends Mock implements GlobalSearchViewModel {}
Add the build_runner package to your project's dev dependencies:
dart pub add dev:build_runner
Import the generated mocks file and annotate it with @GenerateMocks
:
@GenerateMocks([GlobalSearchViewModel])
import 'test_file_name.mocks.dart'; // Replace `test_file_name` with your test file name
Run build_runner
to generate the mocks file:
dart run build_runner build
Run your tests and the "Null is not a subtype of bool" error should not up.
flutter test