gpt4 book ai didi

flutter - 如何测试异步生成器引发的异常?

转载 作者:行者123 更新时间:2023-12-03 03:35:57 25 4
gpt4 key购买 nike

我在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))));

最佳答案

你近了您的第一次尝试:

expect(products, emitsError(AuthException));

不起作用,因为 emitsError Matcher作为其参数,因此您不能直接将其传递给类型。相反,您需要使用 isA<T>() Matcher:

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

关于flutter - 如何测试异步生成器引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61166608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com