使用mockito验证NavigationService popUntil调用

问题描述 投票:0回答:1

我正在为我的 flutter 移动应用程序编写单元测试,并且我正在尝试测试一个函数,该函数在执行时应弹出返回堆栈,直到满足路由函数的谓词为止。这是测试代码和随附的导航代码的示例:

group('popUntilHomeView - ', () {
  test(
      'when popUntilHomeView is called the application should pop the stack until reaching the home screen',
    () {
  // Arrange
  final navigationService = getAndRegisterNavigationServiceMock();
  final viewModel = CurrentViewModel();
  // Act
  viewModel.popUntilHomeView();
  // Assert
  verify(navigationService.popUntil((route) => route.settings.name == 
  '/home-view')).called(1);
  });
});

这是来自 NavigationService 的代码,它构建在 FilledStacked 架构上。

void popUntil(RoutePredicate predicate, {int? id}) {
   G.Get.until(predicate, id: id);
}

这是运行上述测试的结果:

没有匹配的呼叫。所有调用:MockNavigationService.popUntil(Closure: (Route) => bool, {id: null}) (如果您拨打

verify(...).called(0);
,请改为使用
verifyNever(...);
。)

我正在使用 Mockito 来模拟导航服务,这是生成的模拟函数:

 @override
 void popUntil(
 _i8.RoutePredicate? predicate, {
 int? id,
 }) =>
   super.noSuchMethod(
     Invocation.method(
       #popUntil,
       [predicate],
       {#id: id},
      ),
      returnValueForMissingStub: null,
    );

正如您所看到的,函数被调用,它只是没有捕获我定义的谓词,而是返回一个闭包。

问题

有人知道如何验证是否使用正确的谓词调用 NavigationService popUntil 吗?

备注:

  1. 我尝试对函数进行存根操作,该函数取得了一些成功,但我无法对返回值执行任何操作,因为该函数被声明为 void
  2. 我尝试将谓词声明为“any”,以尝试捕获调用详细信息,但由于谓词不可为空,因此不允许。
flutter unit-testing get mockito stacked
1个回答
0
投票

您的 popUntilHomeView() 函数是异步方法吗? 是否需要等待任何非同步方法?.

如果是,请尝试使用await UntilCalled()

await untilCalled(yourAsyncFunction());

verify(navigationService.popUntil((route) => route.settings.name == 
  '/home-view')).called(1);
© www.soinside.com 2019 - 2024. All rights reserved.