单元测试中未调用 Dart Future catchError

Dart Future catchError not called in unit test

我这样调用 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 中捕获错误。你的模拟在被调用时立即(同步地)抛出一个异常;它永远不会 returns 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);
  }
}