Home > Mobile >  In Dart, how to unit test code that emits error internally
In Dart, how to unit test code that emits error internally

Time:04-05

I'm writing a unit test for my custom Dio interceptor. When testing an error case, it executes a piece of code that completes a Completer instance with an error, without actually emitting this error anywhere.

It is reproducible by using this snippet:

void main() {
  test('throws abc', () {
    final completer = Completer();
    completer.completeError('abc');
  });
}

As you can see, the code does not emit the error anywhere, and so there is nothing for me to catch.

The problem is, the test fails for some reason:

00:21  11 -1: test/some_test.dart: throws abc [E]                                                                                                                                                             
  abc
  dart:async                                            _Completer.completeError
  test/some_test.dart 48:15  main.<fn>

How do I make it pass?

CodePudding user response:

Just expect the completer's Future to throw.

test('completes with error abc', () {
  final completer = Completer();
  completer.completeError('abc');
  expect(completer.future, throwsA(equals('abc')));
});

CodePudding user response:

Apparently you have to listen to the future's error:

completer.future.onError((_, __) => valueOnError);

void main() {
  test('throws', () {
    // null works in this case because I'm using a dynamic Completer
    // most likely you will want to provide a concrete value
    const valueOnError = null;

    final completer = Completer();
    completer.future.onError((_, __) => valueOnError);
    completer.completeError('abc');
  });
}
  • Related