Sub topic 5
Testing asynchronous code
Assume you know basic Dart syntax, async and await, and how to run Flutter tests. This chapter focuses on testing code that returns a Future or produces values through a Stream.
Asynchronous code finishes later than the test starts. A test must wait for that work before it checks the result. Otherwise, the test can finish too early or report an error outside the test.
Testing Futures with `async` and `await`
A Future<T> represents one value that will become available later. Mark the test callback with async, then use await for the operation under test.
import 'package:flutter_test/flutter_test.dart';
Future<String> fetchName() async {
await Future<void>.delayed(const Duration(milliseconds: 10));
return 'Ada';
}
Future<String> loadMissingName() async {
await Future<void>.delayed(const Duration(milliseconds: 10));
throw StateError('Name not found');
}
void main() {
test('waits for a Future result', () async {
final name = await fetchName();
expect(name, 'Ada');
});
test('checks a Future error', () async {
expect(
() => loadMissingName(),
throwsA(isA<StateError>()),
);
});
}The test callback returns a Future<void>. The test package waits for that future to complete. The expect call then runs after fetchName has returned.
You can also check a future without await by using the completion matcher:
test('matches a completed Future', () {
expect(fetchName(), completion(equals('Ada')));
});Use await when you need the value for another operation. Use completion when the assertion itself fully describes the expected result.
Testing Streams
A Stream<T> can produce zero, one, or many values over time. expectLater subscribes to the stream and waits for a stream matcher to finish.
import 'package:flutter_test/flutter_test.dart';
Stream<int> countToThree() async* {
yield 1;
yield 2;
yield 3;
}
void main() {
test('checks the order of stream events', () async {
await expectLater(
countToThree(),
emitsInOrder(<dynamic>[
1,
2,
3,
emitsDone,
]),
);
});
}The emitsDone matcher confirms that the stream closes. Other useful matchers include emits, emitsError, and emitsInAnyOrder.
Common errors
- Forgetting
asyncorawaitlets the test finish before the operation completes. - Calling
expectLaterwithoutawaitcan leave a stream assertion running after the test ends. - Adding a fixed delay, such as
Future.delayed(Duration(seconds: 1)), makes tests slow and unreliable. Wait for the actual future or stream condition instead. - Subscribing to a single-subscription stream more than once causes a
StateError. Create a new stream for each test or share one subscription. - Testing only the successful result misses failure behavior. Add tests for thrown exceptions and error stream events.
Exercise
Why must a test using expectLater(stream, emits(...)) usually await the returned value?
Show answer
expectLater returns a Future that completes when the stream matcher receives the expected event. Awaiting it keeps the test alive and reports matcher failures correctly.