1

I have a repository class in my Flutter app with the following method that returns a 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* ...
}

As per this answer on SO, the above way to throw an exception from an async generator function looks fine.

How do I write my test (with test package) so to test the exception thrown by this method?

Something like this does not work:

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));
});

Nor this:

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

Not even this:

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

expect(callback, emitsError(throwsA(predicate((e) => e is AuthException))));
Anurag Bhandari
  • 623
  • 2
  • 6
  • 20

1 Answers1

3

You're close. Your first attempt:

expect(products, emitsError(AuthException));

doesn't work because emitsError takes a Matcher as its argument, so you can't pass it a type directly. Instead, you need to use the isA<T>() Matcher:

expect(products, emitsError(isA<AuthException>()));
jamesdlin
  • 81,374
  • 13
  • 159
  • 204