【问题标题】:Dart Future catchError not called in unit testDart Future catchError 未在单元测试中调用
【发布时间】:2020-12-09 02:26:24
【问题描述】:

我这样称呼 Future:

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

     repository.getDataFromServer().then((result) {
          _handleResult(result);
      }).catchError((e) {
          _handleError(e);
      });
   }

在运行时,当repository出现异常时,会在catchError中被捕获并正确转发。

但是,当我像这样对那部分代码进行单元测试时:

//prepare
when(mockRepository.getDataFromServer()).thenThrow(PlatformException(code: "400", message: "Error", details: ""));

//act

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

//assert

verify(mockRepository.getDataFromServer());

catchError 方法未调用,由于 unHandled 异常,测试失败。

我做错了什么?

【问题讨论】:

    标签: unit-testing flutter dart future flutter-test


    【解决方案1】:

    您的代码希望从返回的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);
      }
    }
    

    【讨论】:

    • 谢谢!! @jamesdlin Future.error 是我想要的!我知道 try catch 解决方案,但是当我使用 Future 时,我更喜欢使用 Future api 来处理错误。
    猜你喜欢
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 2011-06-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 2015-03-05
    相关资源
    最近更新 更多