Sub topic 10
Replacing dependencies with fakes
A widget that talks to a network, a database, or the system clock is hard to test directly. The test would be slow, and its result would depend on something outside your code. This chapter shows how to hand a widget a stand-in dependency, called a fake, that you fully control. You can then test loading, success, and error states in milliseconds.
This chapter assumes you can already write a basic testWidgets test, build a widget with pumpWidget, and use pump and pumpAndSettle. It also assumes you know what a Future is and how FutureBuilder works.
Why real dependencies break widget tests
Widget tests run inside a test binding that replaces the real clock with fake time. Three problems follow from that when a widget uses real services:
- Network calls do not work. In the test environment,
HttpClientreturns HTTP 400 for every request. A widget that loads from a server fails for reasons unrelated to your code. - Real delays are not available. Fake time only moves when you call
pumporpumpAndSettle. Code that waits for real I/O never finishes inside the test. - Results are not repeatable. Data from a live service changes, so assertions on it become flaky.
The fix is dependency injection, which means the widget receives its collaborators from the outside instead of creating them. In production you pass the real implementation. In a test you pass a fake.
Fake, stub, mock: the terms
People use these words loosely. This chapter uses them as follows:
| Term | What it does | Typical use |
|---|---|---|
| Stub | Returns fixed answers | Show a known name on screen |
| Fake | A small working implementation with simple behavior | A repository backed by a `Completer` or a list |
| Mock | Records calls and checks them, often generated by a package | Verify that a method was called with certain arguments |
You do not need a mocking package to start. A hand-written fake that implements an interface is usually enough, and it keeps tests readable.
Step 1: Make the dependency replaceable
Define the dependency as an abstract class. The widget depends on this interface, never on the concrete class.
Then pass the dependency through the constructor. This is the simplest form of injection and needs no packages. The earlier function-based example (loadName) used the same idea with a function type. An interface is better once the dependency has more than one method.
Step 2: Write a fake you can control
The most useful fake for async UI uses a Completer. A Completer is an object that creates a Future and lets you decide when, and how, that future finishes. The test controls the timing exactly, so there is no need to wait for anything.
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class UserRepository {
Future<String> fetchName(String id);
}
class FakeUserRepository implements UserRepository {
final Completer<String> completer = Completer<String>();
final List<String> requestedIds = [];
@override
Future<String> fetchName(String id) {
requestedIds.add(id);
return completer.future;
}
}
class ProfileScreen extends StatefulWidget {
const ProfileScreen({
super.key,
required this.repository,
required this.userId,
});
final UserRepository repository;
final String userId;
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
late final Future<String> _name =
widget.repository.fetchName(widget.userId);
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.hasError) {
return const Text('Could not load profile');
}
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text('Hello, ${snapshot.data}');
},
);
}
}
void main() {
late FakeUserRepository repository;
Future<void> pumpScreen(WidgetTester tester) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ProfileScreen(repository: repository, userId: '42'),
),
),
);
}
setUp(() {
repository = FakeUserRepository();
});
testWidgets('shows a spinner while loading', (tester) async {
await pumpScreen(tester);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(repository.requestedIds, ['42']);
});
testWidgets('shows the name once the future completes', (tester) async {
await pumpScreen(tester);
repository.completer.complete('Ada');
await tester.pump();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Hello, Ada'), findsOneWidget);
});
testWidgets('shows an error message when loading fails', (tester) async {
await pumpScreen(tester);
repository.completer.completeError(Exception('offline'));
await tester.pump();
expect(find.text('Could not load profile'), findsOneWidget);
});
}Notice what each test does:
pumpScreenbuilds the widget once. The fake's future is still pending, so the spinner is on screen.- The first test checks the spinner and also checks
requestedIds, which proves the widget asked for the right user. - The other two tests finish the future by hand, then call
pump()so theFutureBuilderrebuilds with the result.
The setUp callback creates a fresh fake for every test. A fake that is shared between tests carries state from one test to the next. A Completer can only complete once, so reuse would throw a StateError on the second complete call.
Step 3: Script behavior across several calls
Some flows call the same dependency more than once, such as a retry button. A fake can count its calls and behave differently each time.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class UserRepository {
Future<String> fetchName(String id);
}
class FlakyUserRepository implements UserRepository {
int attempts = 0;
@override
Future<String> fetchName(String id) async {
attempts++;
if (attempts == 1) {
throw Exception('offline');
}
return 'Ada';
}
}
class RetryProfile extends StatefulWidget {
const RetryProfile({super.key, required this.repository});
final UserRepository repository;
@override
State<RetryProfile> createState() => _RetryProfileState();
}
class _RetryProfileState extends State<RetryProfile> {
late Future<String> _name = widget.repository.fetchName('1');
void _retry() {
setState(() {
_name = widget.repository.fetchName('1');
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.hasError) {
return Column(
children: [
const Text('Failed'),
ElevatedButton(onPressed: _retry, child: const Text('Retry')),
],
);
}
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
return Text('Hello, ${snapshot.data}');
},
);
}
}
void main() {
testWidgets('retry loads the name after a failure', (tester) async {
final repository = FlakyUserRepository();
await tester.pumpWidget(
MaterialApp(home: Scaffold(body: RetryProfile(repository: repository))),
);
await tester.pumpAndSettle();
expect(find.text('Failed'), findsOneWidget);
await tester.tap(find.widgetWithText(ElevatedButton, 'Retry'));
await tester.pumpAndSettle();
expect(find.text('Hello, Ada'), findsOneWidget);
expect(repository.attempts, 2);
});
}This test uses pumpAndSettle because the fake finishes on its own. There is no Completer to trigger, and no timer is left running afterward. Use the Completer style when you need to look at an intermediate state, such as the spinner. Use the scripted style when you only care about the final result.
Fakes with simulated delays
A fake can also wait with Future.delayed, as in the ProfileName example from the topic overview. Inside testWidgets that delay uses fake time, so it never really waits. The delay finishes when you advance time:
await tester.pump(const Duration(seconds: 1));or when you call pumpAndSettle, which advances time until nothing is scheduled. Prefer the Completer for tests that check loading states. With a delay, the "still loading" state lasts only until the next time advance, so it is easy to step past it by accident.
Other ways to inject
Constructor arguments work well for one or two dependencies, but they get tedious when a dependency is needed deep in the tree. Common alternatives:
- An
InheritedWidgetor a package such asprovider. Wrap the widget under test in the same provider the app uses, but give it the fake. YourpumpScreenhelper then becomes the one place that knows how to build the test tree. - A top-level setup function. If your app uses a service locator, register the fake in
setUpand reset the locator intearDown.
Whichever you use, keep the rule the same: the production code decides what it needs, and the test decides what it gets.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| "A Timer is still pending even after the widget tree was disposed." | The widget or fake started a timer that never finished | Advance time past the timer with `pump(Duration)`, or cancel the timer in `dispose` |
| Spinner never disappears | The fake's future never completed | Call `completer.complete(...)`, then `pump()` |
| `pumpAndSettle` times out | Something keeps scheduling frames, such as an infinite animation or a spinner | Use `pump(Duration)` instead and assert on the state you expect |
| `StateError: Future already completed` | One fake shared between tests | Create the fake in `setUp` |
| Unhandled exception from a failed future | An error completed before anything listened to the future | Complete the error after `pumpWidget`, as in the error test above |
Design guidelines
- Fake at the boundary you own. Fake your own
UserRepository, not the HTTP library underneath it. Your fake then stays valid when the networking code changes. - Keep fakes small. A fake with its own complex logic needs tests itself.
- Assert on what the user sees first. Check recorded calls, such as
requestedIds, only when the call itself is the behavior you care about. - Test the real implementation separately with unit tests. Widget tests with fakes prove the UI reacts correctly. They do not prove the real repository works.
Exercise
A widget calls repository.save(text) when the user taps a Save button. Describe how you would test, without a network, that tapping Save sends the text typed in a field. Which test steps and which fake members are involved?
Show answer
Define a Repository interface with save(String text) and inject it through the widget constructor. Write a FakeRepository that implements it and stores each argument in a List<String> saved. In the test, call pumpWidget with the fake, use tester.enterText(find.byType(TextField), 'hello'), then tester.tap(find.widgetWithText(ElevatedButton, 'Save')) and await tester.pump(). Finally, assert expect(fake.saved, ['hello']). If the UI shows a "Saved" message after completion, make save return a Completer future and complete it before pumping so you can check both states.
Exercise
Why is a Completer-based fake better than Future.delayed for testing that a spinner is shown while loading?
Show answer
With a Completer, the future stays pending until the test completes it, so the loading state remains on screen as long as you need to assert on it. With Future.delayed, the future finishes as soon as fake time advances past the delay, and pumpAndSettle would skip the loading state altogether. The Completer makes the order of events explicit and deterministic.