Sub topic 7
Replacing dependencies with fakes and mocks
Assume you know basic Dart classes, Future, async and await, and how to write a simple unit test. This chapter uses dependency injection: a class receives the services it needs instead of creating them internally.
A test double is a replacement for a real dependency used during a test. It makes the test faster, predictable, and independent of a network, database, or clock.
Fakes and mocks
A fake is a small working implementation with simpler behavior. For example, a fake repository can return users from an in-memory map.
A mock is an object whose behavior you configure for a test. You can also verify how the code used the mock, such as whether a method was called once with a particular argument.
| Test double | Best use | Main strength |
|---|---|---|
| Fake | Testing realistic behavior with simple data | Easy to understand and reuse |
| Mock | Checking calls and controlling difficult cases | Precise interaction verification |
| Stub | Supplying one fixed answer | Minimal setup |
A fake usually tests the result of an operation. A mock can test both the result and the interaction with a dependency.
Inject a dependency
This class receives a UserRepository through its constructor. The production app can pass a real repository, while a test can pass a fake or mock.
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}If Greeter created UserRepository inside its own constructor, replacing the repository would be difficult. Constructor injection keeps the class focused and makes its dependency explicit.
Write a hand-written fake
A fake can return controlled data without using a network.
import 'package:flutter_test/flutter_test.dart';
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName(int id) async {
return switch (id) {
1 => 'Ada',
_ => 'Unknown',
};
}
}
void main() {
test('greets a user returned by the fake repository', () async {
final greeter = Greeter(FakeUserRepository());
expect(await greeter.greet(1), 'Hello, Ada!');
});
}Use a fake when its behavior is meaningful across several tests. For example, a fake local database can store records and expose realistic read and write behavior.
Configure a mocktail mock
Add mocktail as a development dependency in pubspec.yaml:
dev_dependencies:
flutter_test:
sdk: flutter
mocktail: ^1.0.0Create a mock by extending Mock and implementing the interface. Stub the answer with when, then verify the interaction with verify.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('greets the requested user and verifies the call', () async {
final repository = MockUserRepository();
when(() => repository.fetchName(1)).thenAnswer((_) async => 'Ada');
final greeter = Greeter(repository);
expect(await greeter.greet(1), 'Hello, Ada!');
verify(() => repository.fetchName(1)).called(1);
});
}thenAnswer is important for asynchronous methods. It returns a Future instead of a plain string.
Avoid brittle mock tests
A test becomes brittle when it verifies implementation details that do not matter to the user. Verify important boundaries, such as “the repository was asked for this user.” Do not verify every private helper call.
Also stub every dependency response that the test needs. An unstubbed mock method may return an unsuitable default value or fail when the code awaits it.
Exercise
A service should save a profile exactly once after a successful update. Should you use a fake or a mock?
Show answer
Use a mock when the exact save interaction is the requirement. Stub the update result, run the service, and verify that save was called once with the expected profile.