Sub topic 11
Injecting mocks into widget tests
This chapter assumes you know how to write testWidgets tests with WidgetTester, how FutureBuilder and StreamBuilder work, and how to create and stub a mocktail mock (when, thenAnswer, verify). The examples reuse User, UserRepository and MockUserRepository from earlier chapters. They are repeated here so the first file runs on its own.
Why widget tests need injected mocks
A widget test builds real widgets in a fake environment. If ProfilePage creates its own HttpUserRepository, the test would make network calls or fail on missing platform plugins. Passing the repository in through the constructor lets the test supply a mock. The widget code stays the same as in production.
The test controls three things:
- what the dependency returns, including when it returns
- whether it fails
- which calls the widget makes
A widget designed for injection
The first version of ProfilePage created its future inside build. That works, but every rebuild calls fetchUser again. The version below starts the request once in initState, which is also what you want in production.
import 'dart:async';
import 'package:flutter/material.dart';
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);
Future<void> saveUser(User user);
Stream<User> watchUser(String id);
}
class MockUserRepository extends Mock implements UserRepository {}
class ProfilePage extends StatefulWidget {
const ProfilePage({
super.key,
required this.repository,
required this.userId,
});
final UserRepository repository;
final String userId;
@override
State<ProfilePage> createState() => _ProfilePageState();
}
class _ProfilePageState extends State<ProfilePage> {
late final Future<User> _user;
@override
void initState() {
super.initState();
_user = widget.repository.fetchUser(widget.userId);
}
@override
Widget build(BuildContext context) {
return FutureBuilder<User>(
future: _user,
builder: (context, snapshot) {
if (snapshot.hasError) return const Text('Something went wrong');
if (!snapshot.hasData) return const CircularProgressIndicator();
return Text(snapshot.data!.name);
},
);
}
}Building a test harness
Most widgets need an ancestor such as MaterialApp for text direction, themes and navigation. Put that wrapper in one helper so each test reads clearly.
void main() {
late MockUserRepository repository;
setUp(() {
repository = MockUserRepository();
});
Future<void> pumpPage(WidgetTester tester) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ProfilePage(repository: repository, userId: '42'),
),
),
);
}
testWidgets('shows a spinner, then the name', (tester) async {
final completer = Completer<User>();
when(() => repository.fetchUser('42')).thenAnswer((_) => completer.future);
await pumpPage(tester);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
completer.complete(const User('42', 'Ada'));
await tester.pump();
expect(find.text('Ada'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
verify(() => repository.fetchUser('42')).called(1);
});
}The setUp callback creates a fresh mock for every test, so stubs and recorded calls never leak between tests.
Controlling time with a Completer
Stubbing with thenAnswer((_) async => user) completes in the next microtask. By the time you inspect the screen, the loading state may already be gone. A Completer removes that timing problem. The stub returns completer.future, which stays pending until the test calls complete. You can assert on the loading UI, complete the future, pump, and assert on the result.
The same technique tests a slow request that must not finish before the user navigates away.
Choosing how to advance the frame
After the data changes, the widget tree does not update until the test pumps a frame.
| Call | What it does | Use it when |
|---|---|---|
| `tester.pump()` | Runs pending microtasks and builds one frame | A future completed or a stream emitted and you want the next state |
| `tester.pump(Duration)` | Builds a frame after advancing the fake clock | Testing timers, debounce or an animation at a given point |
| `tester.pumpAndSettle()` | Pumps repeatedly until no frames are scheduled | The UI runs several steps or animations to completion |
pumpAndSettle fails with a timeout if something keeps scheduling frames. An indeterminate CircularProgressIndicator does this. If a mocked future never completes while the spinner is on screen, pumpAndSettle never returns. In loading-state tests, use a plain pump().
Testing the error state
A Future-returning method must report failure through the future. thenThrow throws at the moment of the call, before any future exists. In initState that would crash the widget instead of reaching the FutureBuilder's error branch.
testWidgets('shows an error message when the request fails', (tester) async {
when(() => repository.fetchUser(any()))
.thenAnswer((_) => Future<User>.error(Exception('offline')));
await pumpPage(tester);
await tester.pump();
expect(find.text('Something went wrong'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
});Add this test inside main from the previous snippet. Use any() here because the test does not care about the id. Put the literal '42' back when the id is part of what you are checking.
Driving a Stream with a StreamController
A fixed Stream.fromIterable is fine for unit tests. In a widget test, a StreamController lets you emit values at chosen moments and pump between them.
class LiveName extends StatelessWidget {
const LiveName({super.key, required this.repository, required this.userId});
final UserRepository repository;
final String userId;
@override
Widget build(BuildContext context) {
return StreamBuilder<User>(
stream: repository.watchUser(userId),
builder: (context, snapshot) {
if (!snapshot.hasData) return const Text('Waiting...');
return Text(snapshot.data!.name);
},
);
}
}
void main() {
testWidgets('updates when the stream emits', (tester) async {
final repository = MockUserRepository();
final controller = StreamController<User>();
addTearDown(controller.close);
when(() => repository.watchUser('42')).thenAnswer((_) => controller.stream);
await tester.pumpWidget(
MaterialApp(home: LiveName(repository: repository, userId: '42')),
);
expect(find.text('Waiting...'), findsOneWidget);
controller.add(const User('42', 'Ada'));
await tester.pump();
expect(find.text('Ada'), findsOneWidget);
controller.add(const User('42', 'Ada Lovelace'));
await tester.pump();
expect(find.text('Ada Lovelace'), findsOneWidget);
});
}The stub returns the same controller.stream on every call. A rebuild that calls watchUser again would otherwise try to listen to a single-subscription stream twice. addTearDown closes the controller even when the test fails.
Verifying what a user action causes
Widget tests also check that a tap reaches the dependency with the right data. Here a button saves a renamed user. The test uses a fallback value, because any() and captureAny() need one for the custom User type.
class RenameButton extends StatelessWidget {
const RenameButton({super.key, required this.repository, required this.user});
final UserRepository repository;
final User user;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => repository.saveUser(User(user.id, 'Renamed')),
child: const Text('Rename'),
);
}
}
class FakeUser extends Fake implements User {}
void main() {
late MockUserRepository repository;
setUpAll(() {
registerFallbackValue(FakeUser());
});
setUp(() {
repository = MockUserRepository();
when(() => repository.saveUser(any())).thenAnswer((_) async {});
});
Future<void> pumpButton(WidgetTester tester) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RenameButton(
repository: repository,
user: const User('7', 'Grace'),
),
),
),
);
}
testWidgets('does not save before the button is tapped', (tester) async {
await pumpButton(tester);
verifyNever(() => repository.saveUser(any()));
});
testWidgets('saves the renamed user on tap', (tester) async {
await pumpButton(tester);
await tester.tap(find.text('Rename'));
await tester.pump();
final saved = verify(() => repository.saveUser(captureAny()))
.captured
.single as User;
expect(saved.id, '7');
expect(saved.name, 'Renamed');
});
}Pair the two kinds of assertion. Checking the UI proves the user sees the right thing. verify proves the widget asked the dependency to do the right thing. For a command that returns nothing the user can see, such as saveUser, verify is often the only available evidence.
Getting the mock to the widget
Constructor injection is the simplest option and is what this chapter uses. Larger apps often inject through an ancestor widget or a state-management package. The testing approach is the same: wrap the widget under test in whatever supplies dependencies, and give that wrapper the mock.
| Approach | How the test supplies the mock | Trade-off |
|---|---|---|
| Constructor argument | Pass it to the widget directly | Explicit, but must be threaded through intermediate widgets |
| `InheritedWidget` or provider above the widget | Wrap the widget in the same provider with the mock | Less plumbing, but tests must remember to add the wrapper |
| Service locator such as `get_it` | Register the mock before `pumpWidget`, reset after | Global state, so unregister in `tearDown` or tests will interfere |
Common widget-test mistakes
- An unstubbed method returns
null. A Future-returning method that was never stubbed returnsnullinstead of a future. The failure appears inside the widget as a type error, not in the test body. Stub every dependency method the widget calls on first build. - Stubbing after
pumpWidget. IfinitStatecalls the repository, the stub must exist before the widget is pumped. - Creating the future in
build. Each rebuild calls the repository again, andverify(...).called(1)fails with a count of 2 or more. Create the future once ininitState, or keep it in state. - Forgetting to pump. After
controller.addorcompleter.complete, the UI is still old untilpumpruns. pumpAndSettlewith a pending future. The spinner animates forever, so the call times out.- Sharing one mock across tests. Create it in
setUp. Do not create it as afinalat file level.
Exercise
A widget calls repository.fetchUser(id) in initState. Your test uses when(() => repository.fetchUser(any())).thenThrow(Exception('offline')) and expects the text "Something went wrong". The test fails with an uncaught exception. Why, and what is the fix?
Show answer
fetchUser returns a Future, but thenThrow makes the call itself throw synchronously. The exception happens inside initState, before the FutureBuilder receives any future, so the error branch never runs. Stub with thenAnswer((_) => Future<User>.error(Exception('offline'))), then pump() so the FutureBuilder processes the error.
Exercise
Write the test steps to prove that ProfilePage shows a spinner while the request is pending and does not use pumpAndSettle to reach that state. Which object controls when the request finishes?
Show answer
Create a Completer<User> and stub fetchUser with thenAnswer((_) => completer.future). Call await tester.pumpWidget(...) and expect(find.byType(CircularProgressIndicator), findsOneWidget). To finish the request, call completer.complete(const User('42', 'Ada')), then await tester.pump(), then assert that find.text('Ada') finds one widget. The Completer controls the timing. pumpAndSettle would time out while the spinner is animating.