Moti Bartov
Moti Bartov

Reputation: 3592

Dart Future catchError not called in unit test

I am calling Future like this:

   //main_bloc.dart
   ...
    getData() {
     print("getting data");

     repository.getDataFromServer().then((result) {
          _handleResult(result);
      }).catchError((e) {
          _handleError(e);
      });
   }

In runtime, when there is exception from the repository, it will be catched in the catchError and forward properly.

However, when i do unit testing to that part of code like this:

//prepare
when(mockRepository.getDataFromServer()).thenThrow(PlatformException(code: "400", message: "Error", details: ""));

//act

bloc.getData();
await untilCalled(mockRepository.getDataFromServer());

//assert

verify(mockRepository.getDataFromServer());

The catchError method not called and the test is failed due to unHandled exception.

What i am doing wrong?

Upvotes: 0

Views: 768

Answers (1)

jamesdlin
jamesdlin

Reputation: 89995

Your code expects to catch an error from a returned Future. Your mock throws an exception immediately (synchronously) when it is invoked; it never returns a Future.

I think that you instead would need to do:

when(repository.getDataFromServer()).thenAnswer((_) => Future.error(
    PlatformException(code: "400", message: "Error", details: "")));

A simpler (and more robust) change would be to use try-catch in your code instead of Future.catchError:

Future<void> getData() async {
  print("getting data");

  try {
    _handleResult(await repository.getDataFromServer());
  } catch (e) {
    _handleError(e);
  }
}

Upvotes: 3

Related Questions