我在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/