Mock NavigationService cannot verify navigation call
Hi FilledStacks team, I am currently facing an issue where I am testing whether my ViewModel performs a navigation through a mocked NavigationService but it keeps failing due to "No matching calls (actually, no calls at all)."
Inside my ViewModel, this is the navigation function that I am testing:
/// Navigate to Register Page
navigateToRegisterPage() async {
await _navigationService.pushNamedAndRemoveUntil('/register-view');
}
Below is the test, which has registerServices() and getAndRegisterNavigationServiceMock() functions that are based from the FilledStacks Mock Testing guide.
void main() {
group('LoginViewmodelTest -', () {
registerServices();
final model = LoginViewModel();
// ...
test('navigateToRegisterPage() should perform appropriate navigation.',
() async {
var navigationService = getAndRegisterNavigationServiceMock();
await model.navigateToRegisterPage();
verify(navigationService.pushNamedAndRemoveUntil('/register-view'));
});
});
}
Inside test_helpers.dart, I have the following code:
class NavigationServiceMock extends Mock implements NavigationService {}
void registerServices() {
final navigationService = NavigationServiceMock();
// ...
locator.registerSingleton<NavigationService>(navigationService);
// ...
}
NavigationService getAndRegisterNavigationServiceMock() {
_removeRegistrationIfExists<NavigationService>();
final navigationService = NavigationServiceMock();
locator.registerSingleton<NavigationService>(navigationService);
return navigationService;
}
void _removeRegistrationIfExists<T>() {
if (locator.isRegistered<T>()) {
locator.unregister<T>();
}
}
With these, the test still fails even if I change the navigation to replaceWith() instead of pushNamedAndRemoveUntil(). What confuses me more is that when run, the actual program navigates properly, so it's only the test that fails and I am not sure why. I am new to TDD so please bear with me if I have made any stupid mistakes. Thank you in advance!
@BrylleGomez this is because of your verification check. you should change it to include the arguments.
verify(navigationService.replaceWith('RouteName', arguments: anyNamed('arguments'));
It's some extra code for now but until the hashcode or equality operator is implemented to compare the property values for arguments class we have to do this.
Did you checkout the verify call above?
Apologies for the late reply, wasn't able to work yesterday. I just tried it now but with no luck. Below are screenshots. Is this fix supposed to also work with pushNamedAndRemoveUntil() or only with replaceWith()?


Show me the code for navigateToLoginPage
Here it is:
/// Navigate to Login Page
navigateToLoginPage() async {
await _navigationService.pushNamedAndRemoveUntil('/');
}
You're registering your mock navigation after your viewmodel has been constructed. You should construct it in that test.
Ohhh so this order does matter. It fixed it, thank you!!