我试图模拟AutoRouteObserver()类来测试我的项目中的导航,但是当我在navigatorObservers参数中使用模拟示例时,我出现了以下错误:
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following MissingStubError was thrown building AutoRouteNavigator(state:
_AutoRouteNavigatorState#0b446):
'navigator'
No stub was found which matches the arguments of this method call:
navigator
Add a stub for this method using Mockito's 'when' API, or generate the mock for
MockNavigationHistoryObserver with 'returnNullOnMissingStub: true'.
The relevant error-causing widget was:
AutoRouteNavigator
下面是我代码:
void main() async {
var authManagerMock = getAndRegisterAuthManagerMock();
var mockRepository = getAndRegisterRepositoryMock();
final _appRouter = AppRouterAutoRoute(authGuard: AuthGuard());
var mockAutoRouterObserver = MockAutoRouteObserver();
Widget makeTestableWidget() {
when(authManagerMock.isLoggedIn()).thenAnswer((realInvocation) => false);
return MaterialApp.router(
routerDelegate: AutoRouterDelegate(_appRouter, navigatorObservers: () => [mockAutoRouterObserver]),
routeInformationParser: _appRouter.defaultRouteParser());
}
testWidgets('Tapping forgot password text', (WidgetTester tester) async {
await tester.pumpWidget(makeTestableWidget());
await tester.pump();
Finder forgetPasswordButtonFinder = find.byKey(Key('forget-password-button'));
expect(find.byKey(Key('forget-password-button')), findsOneWidget);
await tester.tap(forgetPasswordButtonFinder);
await tester.pumpAndSettle();
expect(find.byKey(Key('forget-password-button')), findsNothing);
expect(find.byKey(Key('submit')), findsOneWidget);
verify(mockAutoRouterObserver.didPush(any, any));
});
}
1条答案
按热度按时间6yt4nkrj1#
您需要确保Mockito可以找到相关的模拟。我就是这么做的。首先,将MockSpec添加到@GenerateMocks或@GeneratorNiceMocks代码中,使用如下符号
然后定义Mock和我们需要用来模拟它的实现
然后从shell运行build_runner,让mocki生成您的mock。
这应该会自动生成大量的mocking代码,看起来像这样:
然后在测试中,像这样验证你的appRouter调用。我们使用get_it将appRouter的真实的实现与mock实现进行交换,但有多种方法可以实现这一点。