Sub topic 10
Testing with fakes and overrides
This chapter assumes you know Dart abstract classes and implements, and basic flutter_test usage (test, testWidgets, expect). It also assumes you have read the earlier chapters on constructor injection, abstractions, Provider, get_it, and Riverpod. The UserRepository and ProfileViewModel types from those chapters appear again here.
Why injection makes tests possible
A unit test should check one piece of logic. If ProfileViewModel created ApiUserRepository inside its own body, every test would hit the network. The test would be slow, would fail when the server is down, and could not produce a specific failure on demand.
Constructor injection removes this problem. The view model asks for a UserRepository, so a test can pass in any class that implements that interface. A test double is any object that stands in for a real dependency during a test. The common kinds are:
| Kind | What it does | Typical use |
|---|---|---|
| Stub | Returns fixed answers | Supplying input data |
| Fake | A small working implementation, often in memory | Replacing a repository or database |
| Mock | Records calls and checks them against expectations | Verifying that an interaction happened |
| Spy | A real or fake object that also records calls | Counting or inspecting calls |
This chapter uses hand-written fakes. They need no code generation or extra packages, and they are easy to read. Reach for a mocking package such as mocktail when you must verify exactly which calls were made, or when the interface is too large to fake by hand.
A first unit test with a fake
This is the fake and test from the spine, with the imports it needs:
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ProfileViewModel extends ChangeNotifier {
ProfileViewModel(this._repository);
final UserRepository _repository;
String? name;
Future<void> load(int id) async {
name = await _repository.fetchName(id);
notifyListeners();
}
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
void main() {
test('load stores the name from the repository', () async {
final viewModel = ProfileViewModel(FakeUserRepository());
await viewModel.load(1);
expect(viewModel.name, 'Test User');
});
}Nothing here touches the network or the widget tree. The test constructs the object under test directly, which is the main payoff of constructor injection.
Fakes you can control
A fake that always returns the same value covers only the happy path. Real tests need failures and in-progress states. Give the fake knobs that the test can set.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
class ControllableUserRepository implements UserRepository {
final Completer<String> completer = Completer<String>();
int calls = 0;
@override
Future<String> fetchName(int id) {
calls++;
return completer.future;
}
}
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => throw Exception('offline');
}
void main() {
test('name stays null until the repository answers', () async {
final repository = ControllableUserRepository();
final viewModel = ProfileViewModel(repository);
final pending = viewModel.load(7);
expect(viewModel.name, isNull);
expect(repository.calls, 1);
repository.completer.complete('Ada');
await pending;
expect(viewModel.name, 'Ada');
});
test('load surfaces repository errors', () async {
final viewModel = ProfileViewModel(FailingUserRepository());
await expectLater(viewModel.load(1), throwsA(isA<Exception>()));
expect(viewModel.name, isNull);
});
}A Completer lets the test decide when the future finishes, so you can inspect the state in between. The calls counter turns the fake into a simple spy. The second test records current behavior: this view model does not catch errors. If you later add error handling, this test should change with it.
Widget tests with Provider
In a widget test, the widget under test usually reads its dependencies from the tree. You supply fakes by building a small tree of your own, a miniature composition root, above the widget.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:provider/provider.dart';
class ProfileScreen extends StatelessWidget {
const ProfileScreen({super.key});
@override
Widget build(BuildContext context) {
final name = context.watch<ProfileViewModel>().name;
return Scaffold(body: Center(child: Text(name ?? 'Loading')));
}
}
void main() {
testWidgets('ProfileScreen shows the loaded name', (tester) async {
await tester.pumpWidget(
MultiProvider(
providers: [
Provider<UserRepository>.value(value: FakeUserRepository()),
ChangeNotifierProvider<ProfileViewModel>(
create: (context) =>
ProfileViewModel(context.read<UserRepository>())..load(1),
),
],
child: const MaterialApp(home: ProfileScreen()),
),
);
expect(find.text('Loading'), findsOneWidget);
await tester.pump();
expect(find.text('Test User'), findsOneWidget);
});
}The test uses the same providers as main(), except that Provider<UserRepository>.value supplies the fake. The ProfileViewModel provider is unchanged because it already reads the repository through context.read. Only the leaf dependency is swapped.
The first pump builds the widget while the future is still unresolved, so "Loading" is visible. The second pump runs the microtasks that complete the fake's future and rebuilds after notifyListeners.
Testing with get_it
get_it keeps its registrations in a global instance. A registration made in one test is still there in the next, so tests can affect each other. The fix is to register fakes before each test and reset the container after it.
import 'package:flutter_test/flutter_test.dart';
import 'package:get_it/get_it.dart';
final getIt = GetIt.instance;
void main() {
setUp(() {
getIt.registerLazySingleton<UserRepository>(() => FakeUserRepository());
getIt.registerFactory<ProfileViewModel>(
() => ProfileViewModel(getIt<UserRepository>()),
);
});
tearDown(() async {
await getIt.reset();
});
test('factory builds a view model backed by the fake', () async {
final viewModel = getIt<ProfileViewModel>();
await viewModel.load(1);
expect(viewModel.name, 'Test User');
});
test('each test starts with a clean container', () {
expect(getIt.isRegistered<UserRepository>(), isTrue);
expect(getIt<UserRepository>(), isA<FakeUserRepository>());
});
}If your production setupLocator() registers the real classes, you have two options. You can write a separate setupTestLocator() that registers fakes, or you can call setupLocator() and then replace single entries. Replacing requires getIt.allowReassignment = true or an unregister call first. Without one of these, get_it throws on a duplicate registration. A separate test setup is usually clearer, because the test states exactly what it depends on.
Overrides in Riverpod
Riverpod has overriding built in, so you do not need a reset step. Each ProviderContainer is an isolated set of provider state, and you choose the overrides when you create it.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final userRepositoryProvider = Provider<UserRepository>(
(ref) => throw UnimplementedError('Provide a real repository in main()'),
);
final userNameProvider = FutureProvider.family<String, int>(
(ref, id) => ref.watch(userRepositoryProvider).fetchName(id),
);
void main() {
test('userNameProvider reads from the overridden repository', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider(1).future);
expect(name, 'Test User');
});
}Two details matter here. First, addTearDown(container.dispose) releases the container's state after the test. Second, the provider body throws UnimplementedError, which is a common pattern for a dependency that every entry point must supply. A test that forgets its override then fails loudly instead of silently reaching a real service.
In a widget test, the same overrides go on ProviderScope(overrides: [...], child: ...). Overrides are fixed when the container or scope is created. Do not read a provider and then try to override it afterward in the same container.
Common errors
- State leaking between tests. This happens with getit singletons and with any fake stored in a global or top-level variable. Create fakes inside
setUpor inside each test, and reset getit intearDown. - A real dependency slipping in. A widget calls
getIt<ApiUserRepository>()or constructs a class directly, so your override is bypassed. Always depend on the abstraction, and search the code under test for direct construction of concrete classes. - Provider not found.
ProviderNotFoundExceptionin a widget test means the widget's provider is missing from your test tree. Every provider the widget reads, directly or through another provider, needs to be above it. - Asserting too early. After a call that starts async work, the UI has not updated yet. Use
await tester.pump()for one frame orawait tester.pumpAndSettle()when animations or several steps are involved. - Fakes that drift from the real class. A fake that always succeeds hides bugs in error handling. Add failing and slow variants as shown above, and keep the interface small so the fake stays honest.
What to test at each level
- Unit tests construct the view model or repository directly with fakes. They are fast and need no container.
- Widget tests build a small tree with fake providers or overrides. Use them for how the UI reacts to loading, data, and error states.
- Integration tests use the real composition root, perhaps with only the network layer replaced. Use few of them, to confirm that the pieces are wired correctly.
Because a view model receives its dependencies in its constructor, you can often test it without the DI framework at all. Reserve the framework-specific techniques (ProviderScope overrides, get_it reset) for tests that need the container.
Exercise
A get_it test passes alone but fails when the whole suite runs. The failing test expects getIt<UserRepository>() to return a fresh FakeUserRepository with no recorded calls, but it sees calls == 3. What is the likely cause, and how do you fix it?
Show answer
The repository is registered as a singleton (or lazy singleton) in the global GetIt.instance, and earlier tests left it registered with its state intact. Register fakes in setUp and call await getIt.reset() in tearDown, so each test gets a new instance. Creating the fake inside each test, or registering it with registerFactory, also works.
Exercise
Write a fake UserRepository that lets a test make fetchName fail for one id and succeed for the others, and say why this is more useful than a fake that always succeeds.
Show answer
class SelectiveUserRepository implements UserRepository { SelectiveUserRepository({required this.failingId}); final int failingId; @override Future<String> fetchName(int id) async { if (id == failingId) throw Exception('not found'); return 'User $id'; } } It lets one test cover both the success path and the error path through the same dependency, so error handling in the view model or widget is exercised instead of assumed.