【问题标题】:How to test exceptions thrown from an async generator?如何测试从异步生成器抛出的异常?
【发布时间】:2020-07-24 18:08:29
【问题描述】:

我的 Flutter 应用程序中有一个 repository 类,该类具有以下返回 Stream 的方法:

Stream<List<Product>> getProducts() async* {
  var currentUser = await this._auth.currentUser();

  if (currentUser == null) {
    throw AuthException('not_logged_in',
        'No current user found probably because user is not logged in.');
  }

  yield* ...
}

根据 SO 上的this answer,上述从异步生成器函数抛出异常的方法看起来不错。

如何编写我的测试(使用test 包)以测试此方法引发的异常?

这样的东西不起作用

test('should throw exception when user is not logged in', () {
  final _authSignedOut = MockFirebaseAuth(signedIn: false);
  final _repoWihoutUser = FirebaseProductRepository(
    storeInstance: _store,
    authInstance: _authSignedOut,
  );

  var products = _repoWihoutUser.getProducts();

  expect(products, emitsError(AuthException));
});

也不是这个:

expect(callback, emitsError(throwsA(predicate((e) => e is AuthException))));

甚至不是这个:

var callback = () {
  _repoWihoutUser.getProducts();
};

expect(callback, emitsError(throwsA(predicate((e) => e is AuthException))));

【问题讨论】:

    标签: flutter exception dart stream


    【解决方案1】:

    你已经接近了。您的第一次尝试:

    expect(products, emitsError(AuthException));
    

    不起作用,因为emitsErrorMatcher 作为其参数,因此您不能直接将类型传递给它。相反,您需要使用isA&lt;T&gt;() Matcher

    expect(products, emitsError(isA<AuthException>()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-18
      • 2017-08-13
      • 1970-01-01
      • 2014-05-10
      • 1970-01-01
      • 2013-07-17
      • 2020-08-03
      • 2020-11-24
      相关资源
      最近更新 更多