Sub topic 12
Mocks, fakes or real objects: choosing the right double
This chapter assumes you can write a mocktail mock, stub it with when, and check calls with verify. It also assumes you know how to inject a dependency through a constructor. Here you decide when a mock is the wrong tool and a fake or the real object is better.
The vocabulary of test doubles
A test double is any object that stands in for a real dependency during a test. The word comes from a stunt double in a film. The kinds differ in how much real behavior they carry.
| Kind | What it is | Typical source |
|---|---|---|
| Real object | The production class, unchanged | Your own code |
| Fake | A working, simplified implementation, such as an in-memory store | A class you write by hand |
| Stub | An object that returns canned answers | `Mock` plus `when` |
| Mock | An object you check for how it was called | `Mock` plus `verify` |
In mocktail one class, Mock, plays both the stub and the mock role. You stub with when and you verify with verify, and most tests do both on the same object.
A fake you write yourself
This chapter reuses User and UserRepository from earlier chapters. The code below adds a hand-written fake and a small service to test.
import 'dart:async';
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> fetchUser(String id);
Future<void> saveUser(User user);
Stream<User> watchUser(String id);
}
class InMemoryUserRepository implements UserRepository {
final Map<String, User> _users = {};
final Map<String, StreamController<User>> _controllers = {};
@override
Future<User> fetchUser(String id) async {
final user = _users[id];
if (user == null) throw StateError('No user with id $id');
return user;
}
@override
Future<void> saveUser(User user) async {
_users[user.id] = user;
_controllers[user.id]?.add(user);
}
@override
Stream<User> watchUser(String id) {
final controller = _controllers.putIfAbsent(
id,
() => StreamController<User>.broadcast(),
);
return controller.stream;
}
}
class UserRenamer {
UserRenamer(this._repository);
final UserRepository _repository;
Future<void> rename(String id, String newName) async {
await _repository.fetchUser(id); // throws if the user does not exist
await _repository.saveUser(User(id, newName));
}
}
void main() {
test('rename persists the new name', () async {
final repository = InMemoryUserRepository();
await repository.saveUser(const User('1', 'Ada'));
await UserRenamer(repository).rename('1', 'Ada Lovelace');
expect((await repository.fetchUser('1')).name, 'Ada Lovelace');
});
test('rename fails for an unknown user', () {
final renamer = UserRenamer(InMemoryUserRepository());
expect(renamer.rename('missing', 'Ghost'), throwsStateError);
});
}Neither test mentions how UserRenamer talks to the repository. They check the outcome: after rename, the stored name changed. If you later change rename to call a new updateName method, these tests keep passing as long as the fake supports it and the behavior is the same.
The same service with a mock
A mock is the better tool when the fake would be awkward or when you need to force a situation the fake cannot produce. A timeout is a good example. An in-memory store never times out, but a mock can be told to.
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
// User, UserRepository and UserRenamer as defined above.
class MockUserRepository extends Mock implements UserRepository {}
class FakeUser extends Fake implements User {}
void main() {
late MockUserRepository repository;
setUpAll(() {
registerFallbackValue(FakeUser());
});
setUp(() {
repository = MockUserRepository();
});
test('rename does not save when the lookup times out', () async {
when(() => repository.fetchUser(any()))
.thenThrow(TimeoutException('server too slow'));
await expectLater(
UserRenamer(repository).rename('1', 'Ada Lovelace'),
throwsA(isA<TimeoutException>()),
);
verifyNever(() => repository.saveUser(any()));
});
}This test needs the mock for two reasons. It injects a failure on demand, and it checks that something did not happen. A fake can do the first only if you add a failure switch to it. It cannot do the second without extra recording code.
What each choice costs
Every double trades fidelity against control.
- Real objects give the most fidelity. A bug in the real class shows up in the test. They cost you speed and determinism when the object touches a network, disk, clock or platform channel.
- Fakes give high fidelity at a moderate cost. You write and maintain them. A fake that behaves differently from the real class can make tests pass while production fails. This is called drift.
- Mocks give the most control and the least fidelity. They only do what you stubbed. Tests that verify every call become brittle: a harmless refactor, such as calling
fetchUsertwice instead of once, breaks them even though behavior is unchanged.
A useful rule is to assert on results where you can and on interactions only where the interaction is the result. Sending an analytics event, calling logout or triggering a payment are interactions that matter. A name stored in a repository is state, and you can read it back.
How to decide
The same logic as a table, with examples:
| Dependency | Good choice | Reason |
|---|---|---|
| Price formatter, validator, mapper | Real object | Pure code with no I/O, so replacing it only hides bugs |
| Repository used by many tests | Fake | State persists between calls, so tests read like real usage |
| HTTP client that must return a 500 | Mock | You need an error that is hard to produce otherwise |
| Analytics or logging service | Mock | The call itself is the behavior you care about |
| `DateTime.now()` source | Fake clock or injected function | You need control over time without verifying calls |
Choose per dependency and per test. One test file can use a real formatter, a fake repository and a mock analytics service together.
Keeping fakes honest
The risk of a fake is drift. You can reduce it with a contract test: one set of tests that runs against every implementation of an interface. Run it against the fake all the time. Run it against the real implementation when you can, for example against a test server or a local database.
import 'package:flutter_test/flutter_test.dart';
// User, UserRepository and InMemoryUserRepository as defined above.
void userRepositoryContract(
String name,
UserRepository Function() create,
) {
group('$name satisfies the UserRepository contract', () {
test('fetchUser returns a saved user', () async {
final repository = create();
await repository.saveUser(const User('1', 'Ada'));
expect((await repository.fetchUser('1')).name, 'Ada');
});
test('fetchUser fails for an unknown id', () {
expect(create().fetchUser('missing'), throwsA(anything));
});
test('watchUser emits saved users', () async {
final repository = create();
final names = repository.watchUser('1').map((u) => u.name);
final expectation = expectLater(names, emits('Grace'));
await repository.saveUser(const User('1', 'Grace'));
await expectation;
});
});
}
void main() {
userRepositoryContract('InMemoryUserRepository', InMemoryUserRepository.new);
}Adding the real repository later takes one more line that passes a factory for it. A mock cannot take part in a contract test, because it has no behavior of its own beyond what each test stubs.
Common mistakes in choosing
- Mocking everything by habit. A mock for a pure helper adds stubbing code and removes real coverage. Use the real object.
- Verifying incidental calls.
verify(() => repository.fetchUser('1')).called(1)pins an implementation detail. Verify only calls whose occurrence is the requirement. - Stubbing so much that the test restates the code. If the setup is longer than the production method, a fake is probably clearer.
- A fake that is too clever. Keep it as simple as the contract allows. A fake with its own bugs needs its own tests, and the contract test above is that safeguard.
- Mixing styles on one object. Do not give one test a mock of the repository and then rely on state it never stored. Pick one double per dependency per test.
Exercises
Exercise
A PriceFormatter class turns an integer number of cents into a string like "$12.50". It has no I/O and no state. A CheckoutService uses it. Should you mock PriceFormatter in the CheckoutService tests? Give your reason.
Show answer
No. Use the real PriceFormatter. It is pure, fast and deterministic, so nothing is gained by replacing it. A mock would force you to stub every formatting call and would stop the test from catching a formatting bug.
Exercise
A PaymentGateway has Future<Receipt> charge(int cents). You must test that CheckoutService shows an error when the gateway throws a TimeoutException, and that charge is never called when the cart is empty. Which kind of double fits, and which two mocktail calls do the work?
Show answer
A mock fits. Use when(() => gateway.charge(any())).thenThrow(TimeoutException('slow')) to inject the failure, and verifyNever(() => gateway.charge(any())) to show that no charge happened for an empty cart. If any() is used for a custom argument type, register a fallback value first. Here charge takes an int, so mocktail needs no fallback value.
Exercise
Your InMemoryUserRepository fake passes all your tests, but production fails because the real repository throws on duplicate ids and the fake silently overwrites. What practice would have caught this, and where would the new test live?
Show answer
A contract test. Write a shared test that saves the same id twice and expects the behavior the real repository has. Run it against both the fake and the real implementation. The fake would fail it and be corrected to match the real one.