In Flutter I have a unit test where I am trying to test whether my code is correctly navigating to another page. I use mocktail for testing.
To start I created a mock router as follows:
class MockGoRouter extends Mock implements GoRouter {}
Then I created a router provider to provide the go router to my context:
class MockGoRouterProvider extends StatelessWidget {
const MockGoRouterProvider({
required this.goRouter,
required this.child,
super.key,
});
final MockGoRouter goRouter;
final Widget child;
@override
Widget build(BuildContext context) => InheritedGoRouter(
goRouter: goRouter,
child: child,
);
}
And when pump my widget I do the following:
MaterialApp(
home: MockGoRouterProvider(
goRouter: router ?? MockGoRouter(),
child: widget,
),
Now finally to use this in my tests where I’m trying to test code that calls goRouter.replace I do:
final mockRouter = MockGoRouter();
when(() => mockRouter.replace(any())).thenAnswer((_) async {});
However, when this code runs I get the following error:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following _TypeError was thrown running a test:
type 'Null' is not a subtype of type 'Future<Object?>'
When the exception was thrown, this was the stack:
#0 MockGoRouter.replace (file:///...mock_router.dart:5:7)
#1 GoRouterHelper.replace (package:go_router/src/misc/extensions.dart:116:25)
#2 GetCodeViewController._updateValidationStatus (package:.....)
#3 GetCodeViewController.validateCode (package:....)
<asynchronous suspension>
Unfortunately I can’t find a lot of resources on mocking go_router so any help is appreciated.