gpt4 book ai didi

unit-testing - 在单元测试中未调用Dart Future catchError

转载 作者:行者123 更新时间:2023-12-03 04:39:30 25 4
gpt4 key购买 nike

我这样称呼 future :

   //main_bloc.dart
...
getData() {
print("getting data");

repository.getDataFromServer().then((result) {
_handleResult(result);
}).catchError((e) {
_handleError(e);
});
}
在运行时,如果存储库中存在异常,则它将在catchError中捕获并正确转发。
但是,当我对部分代码进行单元测试时,如下所示:
//prepare
when(mockRepository.getDataFromServer()).thenThrow(PlatformException(code: "400", message: "Error", details: ""));

//act

bloc.getData();
await untilCalled(mockRepository.getDataFromServer());

//assert

verify(mockRepository.getDataFromServer());
未调用 catchError方法,由于未处理的异常,测试失败。
我做错了什么?

最佳答案

您的代码期望从返回的Future中捕获错误。当您的模拟程序被调用时,它立即(同步)抛出一个异常。它从不返回Future
我认为您需要执行以下操作:

when(repository.getDataFromServer()).thenAnswer((_) => Future.error(
PlatformException(code: "400", message: "Error", details: "")));
一个更简单(也更可靠)的更改是在代码中使用 try- catch而不是 Future.catchError:
Future<void> getData() async {
print("getting data");

try {
_handleResult(await repository.getDataFromServer());
} catch (e) {
_handleError(e);
}
}

关于unit-testing - 在单元测试中未调用Dart Future catchError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63493407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com