eeqk
eeqk

Reputation: 3862

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

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?

Upvotes: 0

Views: 624

Answers (1)

Richard Heap
Richard Heap

Reputation: 51682

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

Upvotes: 2

Related Questions