Sub topic 10
Testing with Fakes and Overrides
Assume you know Dart classes, Future, async and await, and basic Flutter state management. This chapter uses constructor injection and Riverpod providers from earlier chapters.
Dependency injection makes a unit test independent of services such as HTTP clients, databases, and device APIs. The test supplies a controlled replacement instead. This replacement is called a fake.
A fake is a small implementation of an abstraction that behaves predictably. For example, a fake repository can return a fixed user name without making a network request.
Testing a class with a fake
The view model depends on UserRepository, not on ApiUserRepository. The test can therefore pass a fake implementation to the constructor.
import 'package:flutter/foundation.dart';
import 'package:test/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 {
int? requestedId;
@override
Future<String> fetchName(int id) async {
requestedId = id;
return 'Test User';
}
}
void main() {
test('load stores the name from the repository', () async {
final fake = FakeUserRepository();
final viewModel = ProfileViewModel(fake);
await viewModel.load(1);
expect(viewModel.name, 'Test User');
expect(fake.requestedId, 1);
});
}This test checks the view model's behavior. It does not check HTTP, JSON parsing, or server availability. Those concerns belong in separate tests for the concrete repository.
A fake can also model failures. For example, its fetchName method could throw an exception so that the view model's error handling can be tested.
Fakes, mocks, and stubs
These terms describe different test doubles:
| Test double | Main purpose | Example |
|---|---|---|
| Fake | A small working replacement | An in-memory repository |
| Stub | Returns prepared values | Always returns `Test User` |
| Mock | Records calls for interaction checks | Verifies `fetchName(1)` was called |
A hand-written fake is often enough for repository tests. Mocking libraries can reduce repetitive code, but they add another dependency and can make tests coupled to implementation details.
Overriding Riverpod providers
Riverpod moves dependency lookup into providers. In production, a provider can create the real repository. A test can override that provider with a fake in a ProviderContainer.
import 'package:riverpod/riverpod.dart';
import 'package:test/test.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class ApiUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Production User';
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async => 'Test User';
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => ApiUserRepository(),
);
final userNameProvider = FutureProvider.family<String, int>(
(ref, id) => ref.watch(userRepositoryProvider).fetchName(id),
);
void main() {
test('provider uses the fake repository', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider(1).future);
expect(name, 'Test User');
});
}The production provider remains unchanged. The override applies only to this container, so tests do not share altered global state.
Choosing what to verify
Test observable behavior: returned values, changed state, emitted errors, and important side effects. Avoid testing private fields or the exact order of internal calls unless that order is part of the contract.
When a test fails, first identify which boundary is involved:
- Use a fake to isolate the class under test.
- Use a repository integration test for HTTP or database behavior.
- Use a widget test when provider wiring and rendering must be checked together.
Exercise
Why can a view model test use a fake repository without changing the view model's source code?
Show answer
The view model depends on the UserRepository abstraction, so any class that implements that abstraction can be passed through its constructor.