Sub topic 12
Mocks, fakes or real objects: choosing the right double
Assume you know Dart classes, Future, Stream, flutter_test, widget tests, and constructor-based dependency injection. This chapter focuses on choosing a test double. A test double is an object that replaces a real dependency during a test.
A dependency is another object that the code under test needs. Examples include a repository, HTTP client, database, clock, or analytics service. Replacing that dependency can make a test faster and more predictable.
The three main choices
A mock is a programmable object that records calls. With mocktail, you decide what it returns and can verify how the code used it. Mocks are useful when the interaction itself matters.
A fake is a small working implementation of an interface. It usually stores data in memory or uses simple rules. A fake tests behavior through results without requiring a real network or database.
A real object is the production implementation, or a production implementation configured for a test environment. Real objects give the most realistic behavior, but they can be slower, harder to control, or dependent on external systems.
| Double | Best for | Main risk |
|---|---|---|
| Mock | Checking calls, arguments, and errors | Tests can depend too much on implementation details |
| Fake | Testing realistic behavior with simple state | The fake may differ from production |
| Real object | Integration and end-to-end confidence | Tests can be slow, costly, or fragile |
Choosing by the question your test asks
Start with the behavior you need to prove.
Use a mock when the question is, “Did this collaborator receive the right command?” For example, a logout service might need to call session.clear() exactly once. A mock can verify that call directly.
Use a fake when the question is, “Does my code work with a repository that stores and retrieves users?” A memory-based repository can support that behavior without starting a database.
Use a real object when the question is, “Do these production components work together?” For example, an integration test might use a real JSON parser, HTTP client, and local test server.
Avoid mocking the class you are testing. Replace its outside dependencies instead. Also avoid verifying every internal call. A test that checks implementation details can fail after a harmless refactor.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User?> findById(String id);
Future<void> save(User user);
}
class MemoryUserRepository implements UserRepository {
final Map<String, User> _users = {};
@override
Future<User?> findById(String id) async => _users[id];
@override
Future<void> save(User user) async {
_users[user.id] = user;
}
}
class UserService {
UserService(this.repository);
final UserRepository repository;
Future<String> rename(String id, String name) async {
final user = await repository.findById(id);
if (user == null) return 'Not found';
await repository.save(User(user.id, name));
return 'Saved';
}
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('uses a mock when the save interaction matters', () async {
final repository = MockUserRepository();
final service = UserService(repository);
const user = User('7', 'Grace');
when(() => repository.findById('7')).thenAnswer((_) async => user);
when(() => repository.save(any())).thenAnswer((_) async {});
expect(await service.rename('7', 'Grace Hopper'), 'Saved');
verify(() => repository.save(any())).called(1);
});
test('uses a fake when repository behavior matters', () async {
final repository = MemoryUserRepository();
final service = UserService(repository);
await repository.save(const User('7', 'Grace'));
expect(await service.rename('7', 'Grace Hopper'), 'Saved');
expect((await repository.findById('7'))?.name, 'Grace Hopper');
});
}The mock test proves that saving happened. It does not prove that the repository actually stores the renamed user. The fake test proves the complete save-and-read behavior of the in-memory implementation.
Common trade-offs
Mocks are fast and precise, but excessive mock verification couples a test to call order and method names. Prefer assertions about visible results unless the interaction is part of the contract.
Fakes are often easier to read and maintain. Keep them small. If a fake grows into a second production system, use a real test database or integration test instead.
Real objects provide valuable confidence, but isolate external services. A real object should not send production requests or depend on the current time unless the test controls those inputs.
Exercise
A unit test must prove that an email service is called with the user's address, but it must never send an email. Which double should you choose, and why?
Show answer
Choose a mock. Stub the email service so it performs no real work, then use verify or captureAny to inspect the address.