Sub topic 5
Stubbing Futures and Streams with mocktail
This chapter assumes you know Dart classes, abstract classes, Future, Stream, async and await, and basic flutter_test tests. It also assumes you can pass a repository into a class through its constructor.
A mocktail mock does not perform real work. By default, a method returns a simple default value or throws when no suitable value exists. Stubbing means defining what the mock should return when the test calls a method.
For asynchronous methods, the timing and value type both matter:
| Method return type | Recommended stub |
|---|---|
| `Future<User>` | `thenAnswer((_) async => user)` |
| `Future<void>` | `thenAnswer((_) async {})` |
| `Stream<User>` | `thenAnswer((_) => stream)` |
Stubbing a Future
Use thenAnswer when the method returns a Future. The callback can be marked async, which makes the returned value a completed future.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('returns the user supplied by the repository', () async {
final repository = MockUserRepository();
const user = User('42', 'Ada');
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => user);
final result = await repository.fetchUser('42');
expect(result.name, 'Ada');
verify(() => repository.fetchUser('42')).called(1);
});
test('returns an asynchronous error', () async {
final repository = MockUserRepository();
when(() => repository.fetchUser('42'))
.thenThrow(StateError('service unavailable'));
expect(
repository.fetchUser('42'),
throwsA(isA<StateError>()),
);
});
}The when callback describes the invocation that mocktail should intercept. The thenAnswer callback runs each time that invocation occurs. This is useful when the result should be created afresh or when the answer depends on the arguments.
You can also return a failed future explicitly:
when(() => repository.fetchUser('42')).thenAnswer(
(_) async => throw StateError('service unavailable'),
);For Future<void>, return an empty asynchronous callback:
abstract class UserWriter {
Future<void> save(User user);
}
class MockUserWriter extends Mock implements UserWriter {}
final writer = MockUserWriter();
when(() => writer.save(any())).thenAnswer((_) async {});
await writer.save(const User('7', 'Grace'));
verify(() => writer.save(any())).called(1);Stubbing a Stream
A stream produces zero or more values over time. Return a new stream from thenAnswer:
test('emits changing user values', () async {
final repository = MockUserRepository();
when(() => repository.watchUser('42')).thenAnswer(
(_) => Stream.fromIterable(const [
User('42', 'Ada'),
User('42', 'Ada Lovelace'),
]),
);
await expectLater(
repository.watchUser('42').map((user) => user.name),
emitsInOrder(['Ada', 'Ada Lovelace']),
);
});expectLater waits for the asynchronous matcher. emitsInOrder checks both the values and their order. Other useful stream matchers include emits, emitsAnyOf, emitsDone, and emitsError.
Common asynchronous mistakes
- Calling the method before defining
when. The call then uses the mock's default behavior. - Forgetting
await. The test can finish before the future completes. - Using
expectdirectly on a stream instead ofexpectLater. - Returning one single-subscription stream for multiple calls. Create a new stream inside
thenAnswer. - Verifying too early. Verify after the code under test has awaited the operation or consumed the required stream events.
Exercise
How should you stub a method with the signature Future<String> loadName() so that it returns Ada?
Show answer
Use when(() => mock.loadName()).thenAnswer((_) async => 'Ada');