Sub topic 5
Testing asynchronous code
This chapter assumes you can write a basic test with expect, you know async, await, Future and Stream in Dart, and you have used group and setUp. It covers how the test runner handles asynchronous work, how to assert on Futures and Streams, how to control time, and the mistakes that make tests pass when they should fail.
How the runner waits for async tests
A test body can return a Future. The runner waits for that Future before it marks the test finished. Declaring the body async is the usual way to get this.
import 'package:flutter_test/flutter_test.dart';
Future<int> parseAfterDelay(String input) async {
await Future<void>.delayed(const Duration(milliseconds: 10));
return int.parse(input);
}
void main() {
test('returns the parsed number', () async {
final result = await parseAfterDelay('42');
expect(result, 42);
});
test('fails with FormatException on bad input', () async {
await expectLater(parseAfterDelay('abc'), throwsFormatException);
});
}The first test awaits the value and uses an ordinary matcher. The second passes the Future itself to expectLater with a matcher that expects an error. Dart turns the exception thrown inside parseAfterDelay into a failed Future, so the matcher sees it.
Each test has a default timeout of 30 seconds. A Future that never completes fails the test with a timeout instead of hanging forever. You can lower the limit for one test with test('...', body, timeout: const Timeout(Duration(seconds: 2))).
Matchers for Futures
You can pass a Future straight to expect or expectLater if the matcher is built for asynchronous values.
| Matcher | Passes when the Future |
|---|---|
| `completion(matcher)` | completes with a value that satisfies `matcher` |
| `completes` | completes with any value |
| `doesNotComplete` | has not completed after a short time (use sparingly) |
| `throwsA(matcher)` | completes with an error that satisfies `matcher` |
| `throwsA(isA<StateError>())` | fails with a `StateError` |
| `throwsException`, `throwsFormatException`, `throwsArgumentError` | fails with that error type |
expect and expectLater do the same checking. The difference is the return value. expectLater always returns a Future that you can await, so use it for asynchronous matchers. Plain expect also keeps the test open until an asynchronous matcher finishes. Awaiting expectLater is still clearer, and it matters when you need to run code after the assertion.
Compare these two ways to test a failure:
// Synchronous function that throws: pass a closure.
expect(() => int.parse('abc'), throwsFormatException);
// Function that returns a failed Future: pass the Future.
await expectLater(parseAfterDelay('abc'), throwsFormatException);If you pass the result of a synchronous throwing call, the exception escapes before expect runs and the test fails with the raw error. Pass a closure for synchronous code and a Future for asynchronous code.
Testing Streams
A Stream delivers zero or more data events, zero or more error events, and then a done event. You can assert on all of them with stream matchers.
import 'package:flutter_test/flutter_test.dart';
Stream<int> countTo(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Stream<int> failsAfterOne() async* {
yield 1;
throw StateError('boom');
}
void main() {
test('emits 1, 2, 3 and then closes', () {
expect(countTo(3), emitsInOrder([1, 2, 3, emitsDone]));
});
test('collects all values with toList', () async {
expect(await countTo(3).toList(), [1, 2, 3]);
});
test('emits an error event', () async {
await expectLater(
failsAfterOne(),
emitsInOrder([1, emitsError(isA<StateError>()), emitsDone]),
);
});
}The stream matchers are:
emits(matcher): the next event is a data event matchingmatcher.emitsInOrder([...]): the listed events arrive in this order. Entries can be plain values, matchers, or other stream matchers.emitsAnyOf([...]): one of the listed alternatives matches.emitsError(matcher): the next event is an error matchingmatcher.emitsDone: the stream closes.neverEmits(matcher): no event matchingmatcherever arrives.mayEmit(matcher): the event is optional.
emitsInOrder matches a prefix unless you add emitsDone. If you leave emitsDone out, extra events after 3 do not fail the test. Add it whenever the exact end of the stream matters.
toList() is the simplest tool for a finite stream, but it waits for the stream to close. On a stream that never closes, such as a periodic timer, it hangs until the timeout. Use take(n) first: await ticker.take(3).toList().
Driving a stream you control
When a class exposes a stream that you feed through a StreamController, set up the expectation first and then push events.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('controller events arrive in order', () async {
final controller = StreamController<int>();
final expectation = expectLater(
controller.stream,
emitsInOrder([1, 2, emitsDone]),
);
controller
..add(1)
..add(2);
await controller.close();
await expectation;
});
}The sequence matters. expectLater subscribes right away and returns a Future. The test then adds events, closes the controller, and awaits the Future from expectLater. A single-subscription stream buffers events until someone listens, so adding events first would also work here. A broadcast stream (StreamController<int>.broadcast()) drops events that arrive before anyone listens. Subscribing first is the safe habit for both kinds.
Controlling time with fake_async
Code that waits on a Timer or Future.delayed makes tests slow if you wait in real time. The fake_async package replaces the clock inside a zone, so you advance time by hand. Add it with flutter pub add --dev fake_async.
import 'package:fake_async/fake_async.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('delayed work runs after 30 seconds', () {
fakeAsync((async) {
var done = false;
Future<void>.delayed(const Duration(seconds: 30)).then((_) => done = true);
async.elapse(const Duration(seconds: 29));
expect(done, isFalse);
async.elapse(const Duration(seconds: 1));
expect(done, isTrue);
});
});
}This test finishes in milliseconds. elapse runs the timers and microtasks that would fire inside the given duration. Code inside fakeAsync must not wait on real I/O, because no real time passes. Real sockets, files and platform channels never complete there.
Widget tests apply the same idea for you. testWidgets runs the body in a fake-async zone, and tester.pump(duration) advances the fake clock. Later chapters cover pump. If a widget test needs real asynchronous work such as file I/O, wrap that part in tester.runAsync(() async { ... }).
Stubbing async dependencies
When a class under test calls an asynchronous dependency, the double must return a Future or Stream. With mocktail, thenAnswer returns one. Failures need extra care.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
try {
final name = await repository.fetchName(id);
return 'Hello, $name!';
} on Exception {
return 'Hello, guest!';
}
}
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('falls back to guest when the repository fails', () async {
final repository = MockUserRepository();
when(() => repository.fetchName(1))
.thenAnswer((_) async => throw Exception('offline'));
expect(await Greeter(repository).greet(1), 'Hello, guest!');
});
}thenThrow throws synchronously when the mocked method is called. For a method that returns a Future, this skips the failed-Future path and exercises different behavior from a real failure. thenAnswer((_) async => throw ...) produces a Future that completes with an error, which matches what a real repository does.
Common errors
- Forgetting
await. If you callexpect(await ..., ...)correctly the test is fine. The problem is an unawaited Future that is not part of an assertion, such asgreeter.greet(1);. The test can finish before the work does, and a later failure is attributed to nothing or to another test. Enable theunawaited_futureslint to catch this. - Asserting before the state changes. After
controller.add(1), a listener may not have run yet. Events are delivered in a later microtask. Await a Future, use a stream matcher, or useawait Future<void>.delayed(Duration.zero)to let queued microtasks run. - Subscribing late to a broadcast stream. Events emitted before
listenare lost, and the test fails with a stream that "ended" without the expected events. - Real delays.
await Future.delayed(const Duration(seconds: 2))in a test makes the suite slow and flaky. UsefakeAsync, or inject the delay as a constructor parameter and passDuration.zero. - Hanging on a stream that never closes.
toList()andemitsDonewait forever on an open stream. Usetake, or cancel the subscription. - Leaking resources between tests. An open
StreamControlleror a running timer from one test can fire in the next. Close controllers and cancel subscriptions intearDown.
Exercise
A class exposes Stream<int> get values backed by a broadcast StreamController<int>. A test calls controller.add(1), then controller.add(2), then expectLater(controller.stream, emitsInOrder([1, 2])), and times out. What is wrong, and how do you fix the test?
Show answer
A broadcast stream drops events that are added before anyone listens. The expectation subscribes after both events were already emitted, so it never sees 1 or 2 and waits until the timeout. Call expectLater first and store its Future, then add the events, then await the stored Future. If the stream should end, also close the controller and put emitsDone at the end of the list.
Exercise
You mock Future<String> fetchName(int id) with when(() => repo.fetchName(1)).thenThrow(Exception('x')). Why can this give a misleading test, and what do you write instead?
Show answer
thenThrow makes the call throw synchronously, but a real asynchronous method returns a Future that completes with an error. Code that handles failures with await and try/catch may behave the same, but code that attaches .catchError or inspects the Future can behave differently. Use thenAnswer((_) async => throw Exception('x')) so the mock returns a failed Future like the real implementation.