我正在为我的 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 吗?
备注:
您的 popUntilHomeView() 函数是异步方法吗? 是否需要等待任何非同步方法?.
如果是,请尝试使用await UntilCalled()
await untilCalled(yourAsyncFunction());
verify(navigationService.popUntil((route) => route.settings.name ==
'/home-view')).called(1);