mockito 找不到与此方法调用的参数匹配的存根:导航器

x7rlezfr  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(105)

我试图模拟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));
  });
}
6yt4nkrj

6yt4nkrj1#

您需要确保Mockito可以找到相关的模拟。我就是这么做的。首先,将MockSpec添加到@GenerateMocks或@GeneratorNiceMocks代码中,使用如下符号

@GenerateNiceMocks([
  MockSpec<AuthService>(),
  // ...
  MockSpec<MockRouter>(as: Symbol('MockAppRouter'))
])

然后定义Mock和我们需要用来模拟它的实现

// workaround to get Mockito to generate StackRouter mocks
class MockRouter extends Mock implements AppRouter, StackRouter {}

然后从shell运行build_runner,让mocki生成您的mock。

dart run build_runner build

这应该会自动生成大量的mocking代码,看起来像这样:

class MockAppRouter extends _i1.Mock implements _i37.MockRouter {
  @override
  List<_i8.AutoRoute> get routes => (super.noSuchMethod(
        Invocation.getter(#routes),
        returnValue: <_i8.AutoRoute>[],
        returnValueForMissingStub: <_i8.AutoRoute>[],
      ) as List<_i8.AutoRoute>);
  @override
  _i8.RouteType get defaultRouteType => (super.noSuchMethod(
  ...

然后在测试中,像这样验证你的appRouter调用。我们使用get_it将appRouter的真实的实现与mock实现进行交换,但有多种方法可以实现这一点。

verify(appRouter.push(SignUpViewRoute())).called(1);

相关问题