Sub topic 5
Stubbing Futures and Streams
This chapter assumes you can write basic flutter_test tests, you know async/await, Future, and Stream, and you have already created a Mock class with mocktail and stubbed a synchronous method with when(...).thenReturn(...). It covers the rules for stubbing methods that return a Future or a Stream, the mistakes that follow from them, and how to control timing so async tests stay deterministic.
Why thenReturn is the wrong tool
thenReturn hands back one fixed object on every call. That is fine for an int or a String. For asynchronous methods it creates two problems.
- A
FutureorStreaminstance created once at stub time is shared by every call. A single-subscriptionStreamcan only be listened to once, so a second call to the method returns a stream that throwsBad state: Stream has already been listened to. - Mocktail rejects the mistake early. Passing a
FuturetothenReturnthrows anArgumentErrorthat tells you to usethenAnswer((_) async => value)instead.
thenAnswer takes a callback that runs each time the stubbed method is called. The callback builds a new Future or Stream per call, which is how the real method behaves.
| Return type of the method | Stub with | Typical callback |
|---|---|---|
| `int`, `String`, plain objects | `thenReturn` | none, pass the value |
| `Future<T>` | `thenAnswer` | `(_) async => value` |
| `Future<void>` | `thenAnswer` | `(_) async {}` |
| `Stream<T>` | `thenAnswer` | `(_) => Stream.fromIterable(...)` |
| Any method that should fail | `thenThrow` or `thenAnswer` | see the next sections |
The shared setup
The examples below use one small file for the types under test. Save it as test/user_repository.dart. The other examples import it with a relative path.
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);
Future<void> saveUser(User user);
Stream<User> watchUser(String id);
}
class GreetingService {
GreetingService(this._repository);
final UserRepository _repository;
Future<String> greet(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}
class MockUserRepository extends Mock implements UserRepository {}Stubbing Futures
A successful Future uses thenAnswer with an async callback. The returned value is wrapped in a completed Future for you.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'user_repository.dart';
void main() {
late MockUserRepository repository;
late GreetingService service;
setUp(() {
repository = MockUserRepository();
service = GreetingService(repository);
});
test('greets the fetched user', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
expect(await service.greet('42'), 'Hello, Ada!');
});
test('saveUser completes without a value', () async {
when(() => repository.saveUser(any())).thenAnswer((_) async {});
await expectLater(repository.saveUser(const User('7', 'Grace')), completes);
});
}The second test calls any() with User. That only works once you register a fallback value, which a later chapter explains. If you run this file as it stands, the second test fails with a message about a missing fallback value. Add setUpAll(() => registerFallbackValue(const User('', ''))); to main to fix it. This is a good first look at how mocktail errors read.
The callback also receives the Invocation. Use it when the answer depends on the arguments.
when(() => repository.fetchUser(any())).thenAnswer((invocation) async {
final id = invocation.positionalArguments.first as String;
return User(id, 'User $id');
});Stubbing failures
A failing Future can be written two ways, and they behave differently.
thenThrow(Exception('offline'))throws synchronously at the moment the method is called. NoFutureis ever returned.thenAnswer((_) async => throw Exception('offline'))returns aFuturethat completes with an error, like a real network call.
Inside an async function such as GreetingService.greet, both end up as the same error, because await repository.fetchUser(...) is evaluated inside the function body. The difference shows when your test or your code handles the returned Future directly.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'user_repository.dart';
void main() {
test('Future.error produces a failed Future, not a thrown error', () async {
final repository = MockUserRepository();
when(() => repository.fetchUser(any()))
.thenAnswer((_) => Future.error(Exception('offline')));
final future = repository.fetchUser('42'); // does not throw here
await expectLater(future, throwsException);
});
test('thenThrow throws before a Future exists', () {
final repository = MockUserRepository();
when(() => repository.fetchUser(any())).thenThrow(Exception('offline'));
expect(() => repository.fetchUser('42'), throwsException);
});
}Prefer the failed-Future form for async methods. A widget that passes repository.fetchUser(id) to a FutureBuilder never sees a synchronous throw in production. With thenThrow the exception escapes from build instead of reaching snapshot.hasError.
Controlling when a Future completes
async => value completes on the next microtask. That is fine for most tests, but you sometimes need to observe the state before completion, such as a loading spinner or a disabled button. A Completer gives you that control.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'user_repository.dart';
void main() {
test('result arrives only after the completer completes', () async {
final repository = MockUserRepository();
final completer = Completer<User>();
when(() => repository.fetchUser('42')).thenAnswer((_) => completer.future);
String? greeting;
final pending = GreetingService(repository)
.greet('42')
.then((value) => greeting = value);
await pumpEventQueue();
expect(greeting, isNull); // still waiting
completer.complete(const User('42', 'Ada'));
await pending;
expect(greeting, 'Hello, Ada!');
});
}pumpEventQueue comes from flutter_test. It lets pending microtasks and timers run, so the isNull check proves the service is really waiting, not just that it has not been scheduled yet.
Different answers on successive calls
Mocktail replaces the previous stub when you call when again for the same call. To change behavior between calls, such as failing once and then succeeding in a retry test, keep a counter in the callback.
var calls = 0;
when(() => repository.fetchUser('42')).thenAnswer((_) async {
calls++;
if (calls == 1) throw Exception('offline');
return const User('42', 'Ada');
});Stubbing Streams
A Stream method is stubbed with thenAnswer returning a stream. Each call then gets its own stream, which avoids the "already listened to" error.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'user_repository.dart';
void main() {
test('emits a fixed sequence, and each call gets a fresh stream', () async {
final repository = MockUserRepository();
when(() => repository.watchUser('42')).thenAnswer(
(_) => Stream.fromIterable(const [
User('42', 'Ada'),
User('42', 'Ada Lovelace'),
]),
);
for (var i = 0; i < 2; i++) {
await expectLater(
repository.watchUser('42').map((u) => u.name),
emitsInOrder(['Ada', 'Ada Lovelace', emitsDone]),
);
}
});
test('emits an error event', () async {
final repository = MockUserRepository();
when(() => repository.watchUser(any()))
.thenAnswer((_) => Stream<User>.error(Exception('lost connection')));
await expectLater(
repository.watchUser('42'),
emitsError(isA<Exception>()),
);
});
}Use emitsDone when the stream should close after its last value. Without it, emitsInOrder passes as soon as the listed values arrive.
Driving a Stream from the test
Stream.fromIterable emits everything immediately. When the test must decide when each event happens, return the stream of a StreamController.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'user_repository.dart';
void main() {
test('reacts to values pushed by the test', () async {
final repository = MockUserRepository();
final controller = StreamController<User>();
addTearDown(controller.close);
when(() => repository.watchUser('42')).thenAnswer((_) => controller.stream);
final names = <String>[];
final subscription =
repository.watchUser('42').map((u) => u.name).listen(names.add);
controller.add(const User('42', 'Ada'));
await pumpEventQueue();
expect(names, ['Ada']);
controller.add(const User('42', 'Ada Lovelace'));
await pumpEventQueue();
expect(names, ['Ada', 'Ada Lovelace']);
await subscription.cancel();
});
}A plain StreamController is single-subscription, so a second call to watchUser in the same test would fail on listen. If the code under test subscribes more than once, create it with StreamController<User>.broadcast(). In a widget test with a StreamBuilder, tester.pump() after controller.add replaces pumpEventQueue.
How the pieces fit
Common mistakes
- Passing a
FutureorStreamtothenReturn. Switch tothenAnswer. - Using
thenThrowfor an async method and then expectingsnapshot.hasError. ReturnFuture.errorinstead. - Building the stream outside
thenAnswerand reusing it across calls. Create it inside the callback, or use a broadcast controller. - Forgetting
awaitbeforeexpectLaterorexpect(..., throwsException)on aFuture. The test finishes before the assertion runs and can pass for the wrong reason. - Leaving a
StreamControlleropen. RegisteraddTearDown(controller.close)so one test does not leak into the next.
Exercise
A test stubs when(() => repository.watchUser('42')).thenAnswer((_) => sharedStream); where sharedStream is a Stream.fromIterable(...) variable declared once at the top of main. The first test passes, but a later test that calls watchUser('42') fails with "Bad state: Stream has already been listened to". Why, and how do you fix it?
Show answer
Stream.fromIterable creates a single-subscription stream, and sharedStream is the same instance for every call. Once the first test listens to it, nobody can listen again. Fix it by creating the stream inside the callback, as in thenAnswer((_) => Stream.fromIterable(...)), so each call gets a new stream.
Exercise
You are testing a widget that wraps repository.fetchUser(id) in a FutureBuilder and shows 'Something went wrong' when snapshot.hasError is true. Which stub should you use to drive the error state, thenThrow(Exception('offline')) or thenAnswer((_) => Future.error(Exception('offline'))), and why?
Show answer
Use thenAnswer((_) => Future.error(Exception('offline'))). It returns a failed Future, which is what the FutureBuilder expects and what produces snapshot.hasError. thenThrow raises the exception inside build when fetchUser is called, so the widget never receives a Future and the test fails with a thrown exception instead.
Exercise
How can a test confirm that a service is still waiting for fetchUser before the result arrives, and then confirm the final value?
Show answer
Stub with thenAnswer((_) => completer.future) using a Completer<User>. Start the call, await pumpEventQueue(), and assert that no result exists yet. Then call completer.complete(user), await the pending call, and assert on the final value.