【问题标题】:Testing side effects in an async function that throw exception in Dart在 Dart 中抛出异常的异步函数中测试副作用
【发布时间】:2021-01-08 20:00:42
【问题描述】:

我想测试一个异步函数的异常行为和副作用。

abstract class Async {
  int count();

  Future<void> throwExceptionAfter(int sec);
}

class ImplAsync extends Async {
  int _count = 0;
  @override
  int count() => _count;

  @override
  Future<void> throwExceptionAfter(int sec) async {
    await Future.delayed(Duration(seconds: sec));

    _count++;

    throw Exception();
  }
}

测试:

void main() {
  Async impl;
  setUp(() {
    impl = ImplAsync();
  });
  group('throwExeptionAfter', () {
    test('simple call with waiting', () async {
      expect(impl.throwExceptionAfter(0), throwsException);

      await Future.delayed(Duration(seconds: 1));

      var count = impl.count();
      expect(count, 1);
    });
    test('simple call', () async {
      expect(impl.throwExceptionAfter(1), throwsException);

      var count = impl.count();
      expect(count, 1);
    });
  });
}

第一个测试“带等待的简单调用”有效,但在此测试中,我等待一段时间以确保该方法完成。第二个测试不起作用,因为在方法完成之前首先检查计数的测试。

有没有办法像这样等待期望:

test('simple call', () async {
  await expect(impl.throwExceptionAfter(1), throwsException);

  var count = impl.count();
  expect(count, 1);
});

我已经尝试了几种可能性,但到目前为止找不到解决方案。文档也没有帮助我。 Asynchronous Tests

我的测试可以在这里找到:Github

感谢您的帮助。

【问题讨论】:

    标签: unit-testing dart asynchronous testing async-await


    【解决方案1】:

    我找到了几种解决方案。 一种解决方案是将方法打包到 try-catch 块中:

    test('simple call wiht try catch', () async {
      try {
        await impl.throwExceptionAfter(1);
      } catch (e) {
        expect(e, isInstanceOf<Exception>()); 
      }
    
      var count = impl.count();
      expect(count, 1);
    });
    

    另一种解决方案是在方法whenComplete中进行检查:

    test('simple call with whenComplete', () async {
      expect(
        impl.throwExceptionAfter(1).whenComplete(() {
          var count = impl.count();
          expect(count, 1);
        }),
        throwsException);
    });
    

    我希望答案对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-01-02
      • 2015-06-04
      • 1970-01-01
      • 2017-08-13
      • 2021-05-25
      • 2012-09-29
      • 2018-04-09
      • 2018-10-02
      相关资源
      最近更新 更多