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

问题描述

我这样称呼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);
  }
}