Sub topic 1
Why mock dependencies in tests
A unit test should fail for one reason: the code under test is wrong. Real dependencies add other reasons. The network can be down, a database can hold stale rows, and a clock can tick past midnight. This chapter explains why replacing those dependencies with controlled stand-ins makes tests faster and more deterministic. It also covers what that costs and when you should not do it. Later chapters show how to do it with the mocktail package.
Prerequisites
This chapter assumes you already know the following:
- Dart basics: classes, abstract classes, interfaces,
async/await, Futures and Streams. - How to write simple tests with
flutter_test:test,group,expectandsetUp. - The basic
testWidgetsandWidgetTesterworkflow. - How to pass an object into a class through its constructor.
You do not need mocktail yet. The examples here use hand-written stand-ins, so you can see the problem before you meet the tool.
What counts as a dependency
A dependency is anything your code needs but does not own. In a Flutter app the usual ones are:
- A repository or API client that talks to a server.
- A local database or
SharedPreferences. - Platform services such as the camera, location, or secure storage.
- The system clock and random number generators.
- Another class with its own logic, such as an authentication service.
The class you are testing is the system under test (SUT). When the SUT calls a dependency, the test result depends on that dependency's behavior as well as the SUT's own.
What goes wrong with real dependencies
Tests that touch real dependencies have predictable problems.
| Problem | Cause | Effect on your test suite |
|---|---|---|
| Slow | Network round trips, disk I/O, plugin startup | A suite that took seconds takes minutes, so people stop running it |
| Flaky | Timeouts, rate limits, changing server data, clock reads | The same code passes and fails on different runs |
| Hard to set up | You need an account, a seeded database or a running backend | New contributors and CI cannot run the tests |
| Unable to reach error paths | You cannot make a healthy server return a 500 on demand | Error handling goes untested |
| Unsafe | A test might write to or delete from production data | Tests cause real damage |
| Poor failure signal | A failure may come from the dependency, not your code | You debug the wrong thing |
Unit tests in flutter_test also run in a Dart VM test environment. Platform channels such as camera, location, and secure storage have no real implementation there. A test that reaches them directly fails or hangs, whatever the quality of your code.
The error-path row matters most. Most bugs in networked apps appear when something fails: offline, expired token, malformed response. You can only test those situations reliably if the test controls what the dependency does.
Isolation: the core idea
Isolating the SUT means you decide what each dependency returns, throws, or emits, and you can observe how the SUT used it. That gives you two properties:
- Determinism. The same inputs always produce the same result. A stand-in that returns
User('42', 'Ada')returns exactly that every time. - Speed. A stand-in is an in-memory object. A call costs microseconds, so thousands of tests run in seconds.
Isolation also narrows the question each test asks. A test of GreetingService asks "given this repository response, does the service produce the right greeting?" It does not ask whether the server is up.
Test doubles: the vocabulary
A test double is any object that stands in for a real dependency during a test. The word comes from "stunt double". People use several names for specific kinds, and the differences matter later when you choose between them.
| Kind | What it does | Typical use |
|---|---|---|
| Dummy | Fills a parameter and is never used | A constructor needs an argument the test does not exercise |
| Stub | Returns canned answers | "When asked for user 42, return Ada" |
| Fake | A simplified but working implementation | An in-memory repository backed by a `Map` |
| Mock | Records calls so the test can verify them, and can also be stubbed | "The service called `saveUser` exactly once" |
| Spy | Wraps a real object and records calls | Observing the real behavior while checking interactions |
These categories overlap in practice. In mocktail, one object can be stubbed (act as a stub) and verified (act as a mock). Chapter 13 of this tutorial returns to the mock-versus-fake choice.
A worked example without any library
The service and repository below are the running example for the whole tutorial. The repository is an abstract class, so any class can implement it.
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
}
class GreetingService {
GreetingService(this._repository);
final UserRepository _repository;
Future<String> greet(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}A real implementation would call an HTTP API. To test GreetingService without it, write two small hand-made doubles in the test file and pass them to the constructor.
import 'package:flutter_test/flutter_test.dart';
class User {
const User(this.id, this.name);
final String id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
}
class GreetingService {
GreetingService(this._repository);
final UserRepository _repository;
Future<String> greet(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}
class StubUserRepository implements UserRepository {
@override
Future<User> fetchUser(String id) async => const User('42', 'Ada');
}
class OfflineUserRepository implements UserRepository {
@override
Future<User> fetchUser(String id) async => throw Exception('offline');
}
void main() {
test('greets the user returned by the repository', () async {
final service = GreetingService(StubUserRepository());
expect(await service.greet('42'), 'Hello, Ada!');
});
test('propagates repository failures', () async {
final service = GreetingService(OfflineUserRepository());
expect(service.greet('42'), throwsException);
});
}Both tests run in milliseconds with no network. The second test reaches an error path that a healthy server would never trigger.
This approach has a cost. Each scenario needs its own class, and the test cannot check how the service used the repository. To check that fetchUser was called once with '42', you would add counters and fields by hand to every double. mocktail removes that boilerplate: you create one mock per interface and configure it per test. The next chapters build up to it.
Why the abstract class matters
The tests above work because GreetingService depends on the UserRepository interface, not on a concrete HTTP class. Dart gives every class an implicit interface, so any class can be implemented. An abstract class still states the contract clearly. The service also receives the repository through its constructor instead of creating it itself.
If GreetingService built its own HttpUserRepository inside greet, the test could not substitute anything. Mocking depends on this design, which is why the next chapter covers designing code so dependencies can be replaced.
What mocking costs
Mocks are not free, and a test suite full of them can mislead you.
- Doubles can drift from reality. A stub says
fetchUserreturns aUser. If the real server starts returningnullfor unknown users, your tests keep passing while the app breaks. - Tests can couple to implementation. If you verify that the service called three specific methods in order, any harmless refactor breaks the test. Verify the interactions that matter, such as a save or an analytics event, and assert on outputs for everything else.
- Mocks cannot test integration. A passing unit test with a mocked repository says nothing about whether the real repository parses the real JSON correctly.
The usual answer is layers of tests. Unit and widget tests use doubles for speed and precision. A smaller number of integration tests use real components to confirm the pieces fit together.
When not to mock
Mock the boundaries of your system, not everything. A few rules of thumb:
- Mock things that are slow, nondeterministic, or have side effects: network, disk, platform channels, time.
- Do not mock simple value objects such as
User. Construct a real one. - Do not mock the class under test. If you stub the method you are trying to test, the test proves nothing.
- Prefer a real object when it is fast, deterministic, and easy to build, such as a pure formatting helper.
- Do not mock types you do not own unless you wrap them in your own interface first. Mocking a third-party class couples your tests to its internals.
Common mistakes at this stage
- Testing the mock. A test that stubs
fetchUserto return Ada and then asserts the repository returns Ada exercises only the double. - Over-verifying. Checking every call makes tests brittle. Verify side effects and outputs that matter to the behavior.
- Hiding a missing seam. If a class is hard to test, the cause is often a hard-coded dependency. Fix the design before adding workarounds.
- Treating mocks as a substitute for integration tests. Doubles prove your logic is correct given an assumption about the dependency. They do not prove the assumption.
Where this goes next
The remaining chapters take the example above and build it up with mocktail: adding the package, stubbing with when, handling Futures and Streams, matching and capturing arguments, verifying calls, isolating tests, and finally injecting mocks into widget tests.
Exercise
A test for GreetingService uses the real HttpUserRepository and passes on your laptop but fails intermittently on CI. Name two reasons mocking the repository would help, and one thing the mocked test still cannot tell you.
Show answer
The mocked test is deterministic, because the double returns the same data on every run, so intermittent timeouts, rate limits, or changing server data cannot cause failures. It is also fast and needs no network or credentials on CI. It cannot tell you whether the real HttpUserRepository talks to the real server and parses the response correctly. That needs an integration test.
Exercise
Why does GreetingService take a UserRepository through its constructor instead of creating an HttpUserRepository inside greet?
Show answer
Constructor injection lets a test pass in a double. If the service created the HTTP repository itself, every test would hit the real network and the test could not control the response.
Exercise
Which of these should you mock in a unit test: a User value object, an HTTP client, DateTime.now() used for expiry logic, or the GreetingService you are testing? Give a one-line reason for each.
Show answer
Mock the HTTP client (slow, nondeterministic, side effects). Control DateTime.now() by injecting a clock or time function (nondeterministic). Do not mock User (a simple value object, so build a real one). Do not mock GreetingService (it is the code under test, and stubbing it proves nothing).