Sub topic 10
Replacing Dependencies with Fakes
This chapter assumes you know basic Dart async and await, Flutter widget lifecycles, testWidgets, WidgetTester, finders, and matchers. You should also know how to run flutter test.
A widget often depends on something outside the widget tree, such as an HTTP client, database, clock, or repository. A widget test should not call a real server. A fake is a small test implementation that returns controlled data. Dependency injection is the practice of giving a widget its dependencies from the outside instead of creating them inside the widget.
Why inject dependencies?
Suppose a profile widget loads a name. If the widget creates its own API client, the test cannot easily control the response. If the widget receives a repository in its constructor, the test can provide a fake repository.
This arrangement separates two concerns:
- The widget displays loading, success, and error states.
- The repository decides where data comes from.
Build a widget around an injected repository
The repository is an abstract contract. Production code can provide a network implementation, while a test provides a fake.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class ProfileRepository {
Future<String> loadName();
}
class FakeProfileRepository implements ProfileRepository {
@override
Future<String> loadName() {
return Future<String>.delayed(
const Duration(seconds: 1),
() => 'Ada',
);
}
}
class ProfileName extends StatefulWidget {
const ProfileName({super.key, required this.repository});
final ProfileRepository repository;
@override
State<ProfileName> createState() => _ProfileNameState();
}
class _ProfileNameState extends State<ProfileName> {
late final Future<String> _name = widget.repository.loadName();
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: _name,
builder: (context, snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return const CircularProgressIndicator();
}
if (snapshot.hasError) {
return const Text('Could not load profile');
}
return Text('Hello, ${snapshot.data}');
},
);
}
}
void main() {
testWidgets('shows loading, then the fake profile name', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ProfileName(repository: FakeProfileRepository()),
),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Hello, Ada'), findsOneWidget);
});
}pumpWidget creates the initial tree. The delayed fake leaves the widget in its loading state first. pumpAndSettle repeatedly advances test frames and fake time until pending work finishes. It does not wait one real second.
Test failure states with different fakes
A useful fake can be configured for several outcomes. For example, a failing fake can return Future.error('network failure'). Then the test can assert that Could not load profile appears.
Keep fakes predictable. Do not add random failures or real network calls. If the dependency has many behaviors, create separate fakes or constructor options for each scenario. This makes each test explain exactly which state it covers.
Exercise
Exercise
How would you test the error message without changing the ProfileName widget?
Show answer
Create a fake repository whose loadName method returns Future.error('failure'), pass it to ProfileName, call pumpAndSettle, and expect find.text('Could not load profile') to find one widget.