Sub topic 10
Keeping tests isolated with setUp and reset
This chapter assumes you can write test and testWidgets cases, that you know how to create a Mock subclass, and that you can stub with when and check calls with verify. It covers how mock state leaks between tests, and how to prevent that with setUp, reset, and clearInteractions.
Why a mock carries state
A mock object remembers two things:
- Stubs. Each
when(...)call registers a response. Later calls that match it get that response. - Interactions. Every call made on the mock is recorded.
verifycounts these recorded calls.
Both live inside the mock instance. If two tests share one instance, the second test starts with the first test's stubs and call history. A test that passes alone then fails in the full suite, or passes only when it runs after another test.
Isolated tests have the same result in any order and when run alone. Test runners can shuffle order, and you will often run a single test while debugging, so isolation is a requirement.
A leaking test
Here is the code under test, as in earlier chapters. All the snippets below belong in the same test file.
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 GreetingService {
GreetingService(this._repository);
final UserRepository _repository;
Future<String> greet(String id) async {
final user = await _repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}
class MockUserRepository extends Mock implements UserRepository {}This main creates the mock once, outside any test callback:
void main() {
final repository = MockUserRepository();
final service = GreetingService(repository);
test('greets Ada', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
expect(await service.greet('42'), 'Hello, Ada!');
verify(() => repository.fetchUser('42')).called(1);
});
test('greets Ada again', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
expect(await service.greet('42'), 'Hello, Ada!');
verify(() => repository.fetchUser('42')).called(1); // fails
});
}The second test fails because the mock has now recorded two fetchUser('42') calls. verify(...).called(1) sees two. Run the second test alone and it passes, which makes the failure confusing. The mock is the shared state.
The same leak affects stubs. A thenThrow registered in one test stays active in the next test that calls the same method with matching arguments, unless that test registers a newer stub for it.
The default fix: a fresh mock in setUp
The simplest way to isolate tests is to build every object under test inside setUp. setUp runs before each test and each testWidgets in its scope.
void main() {
late MockUserRepository repository;
late GreetingService service;
setUp(() {
repository = MockUserRepository();
service = GreetingService(repository);
});
test('greets Ada', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
expect(await service.greet('42'), 'Hello, Ada!');
verify(() => repository.fetchUser('42')).called(1);
});
test('greets Ada again', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
expect(await service.greet('42'), 'Hello, Ada!');
verify(() => repository.fetchUser('42')).called(1); // passes
});
}Notes on this pattern:
- Declare the variables with
lateand assign them insetUp. Each test then gets new instances. - Rebuild the object under test too. If
serviceheld its own state, such as a cache, reusing it would leak that state even with a fresh mock. - Keep
setUpfree of stubs that only some tests need. Put shared defaults there only if every test in the group relies on them. Put test-specific stubs in the test, so a reader sees the whole scenario in one place.
Resetting a mock you cannot recreate
Sometimes one mock instance has to outlive a single test. A singleton wired through a service locator is an example. A const configuration or a long-lived object graph built once is another. Recreating the mock is not an option there, so mocktail offers two functions.
| Function | Removes stubs | Removes recorded calls | Typical use |
|---|---|---|---|
| `reset(mock)` | Yes | Yes | Return a long-lived mock to its initial state between tests |
| `clearInteractions(mock)` | No | Yes | Start counting calls again inside one test, keeping the stubs |
A mock that has been reset behaves like a new one. An unstubbed method on a mocktail mock returns null, so a method that returns Future<User> fails with a type error when called. Stubs and call counts both disappear.
void main() {
final repository = MockUserRepository(); // long-lived on purpose
final service = GreetingService(repository);
setUp(() {
reset(repository);
});
test('first test', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
await service.greet('42');
verify(() => repository.fetchUser('42')).called(1);
});
test('second test starts clean', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Grace'));
expect(await service.greet('42'), 'Hello, Grace!');
verify(() => repository.fetchUser('42')).called(1);
});
}Calling reset in setUp rather than tearDown has one advantage. If a previous test crashed halfway, the next test still starts from a known state.
Clearing interactions inside one test
clearInteractions is useful when a single test has several phases and you want to count calls in each phase separately. Think of a screen that loads data, then refreshes it.
void main() {
late MockUserRepository repository;
late GreetingService service;
setUp(() {
repository = MockUserRepository();
service = GreetingService(repository);
});
test('a second greet calls the repository again', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
await service.greet('42');
verify(() => repository.fetchUser('42')).called(1);
clearInteractions(repository);
await service.greet('42');
verify(() => repository.fetchUser('42')).called(1);
verifyNoMoreInteractions(repository);
});
}After clearInteractions, the stub for fetchUser('42') still works, so the second greet succeeds. The count restarted at zero, so the second called(1) checks only the second phase. Without the clear, the second check would see two calls and fail.
verifyNoMoreInteractions(repository) fails if the mock received any call that no earlier verify accounted for. It is a strict check. Use it where an unexpected call would be a bug, such as asserting that a cached path does not hit the network. Avoid it as a default, because it makes tests fail when you add harmless calls.
Two details of how mocktail counts calls:
- The call inside
when(() => ...)is not recorded as an interaction. Stubbing does not add to the counts thatverifysees. - Calls made by
verifyitself are not recorded either.
Cleaning up resources a mock hands out
Isolation also covers objects that your stubs create. A StreamController returned from a stubbed watchUser must be closed, or it leaks into later tests and can keep the process alive. Register the cleanup with addTearDown at the point where you create the resource.
void main() {
late MockUserRepository repository;
setUp(() {
repository = MockUserRepository();
});
test('emits each pushed user', () async {
final controller = StreamController<User>();
addTearDown(controller.close);
when(() => repository.watchUser('42')).thenAnswer((_) => controller.stream);
final names = repository.watchUser('42').map((u) => u.name);
final expectation = expectLater(names, emitsInOrder(['Ada', 'Ada Lovelace']));
controller
..add(const User('42', 'Ada'))
..add(const User('42', 'Ada Lovelace'));
await expectation;
});
}This test needs import 'dart:async'; at the top of the file for StreamController. addTearDown runs after the current test whether it passes or fails, and it keeps the creation and the cleanup next to each other. A separate tearDown would need a late variable for the controller.
Choosing where each call belongs
| Hook | Runs | Put here |
|---|---|---|
| `setUpAll` | Once before the group | `registerFallbackValue`, expensive read-only fixtures |
| `setUp` | Before every test | New mocks, new objects under test, `reset` for long-lived mocks |
| Test body | Once | Stubs specific to the scenario, `verify`, `clearInteractions` between phases |
| `addTearDown` | After the current test | Closing controllers, subscriptions, and similar resources |
| `tearDown` | After every test | Cleanup that every test in the group needs |
Finding leaks you already have
Order dependence hides until the order changes. Ask the runner to shuffle tests with a random seed:
flutter test --test-randomize-ordering-seed=randomThe runner prints the seed it used. If a shuffled run fails, rerun with that seed, for example --test-randomize-ordering-seed=12345, to reproduce the failure. Running the failing test alone with --plain-name 'greets Ada again' tells you whether it depends on an earlier test.
Typical signs of leaked mock state:
- A
verify(...).called(1)fails with an actual count of 2 or more. - A test passes alone and fails in the suite.
- A test expecting data gets an exception that an earlier test stubbed with
thenThrow. verifyNeverfails for a call your test never made.
Widget tests follow the same rule
setUp also runs before each testWidgets, so the pattern is identical. Create the mock in setUp, stub it in the test, and pass it through the constructor. The widget tree from a previous testWidgets is already torn down, so the only shared state to worry about is your mock and any global singletons.
Exercise
A test file declares final repository = MockUserRepository(); inside main, and no test calls reset. Test 1 calls verify(() => repository.fetchUser('42')).called(1) and passes. Test 2 makes the same call and the same verify, but it fails. Why, and what are two ways to fix it?
Show answer
The mock is shared, so it recorded the fetchUser('42') call from test 1 and test 2's call makes the count 2. Fix 1: declare late MockUserRepository repository; and assign a new mock (and a new service) in setUp. Fix 2: keep the shared mock and call reset(repository) in setUp, which clears both stubs and recorded calls. Fix 1 is preferred because it also resets any state in the object under test.
Exercise
Within one test you call service.greet('42'), verify it, then call clearInteractions(repository) and call service.greet('42') again. Does the second call still receive the stubbed User? What would reset(repository) have done instead?
Show answer
Yes. clearInteractions removes only the recorded calls, so the stub for fetchUser('42') still answers and the second verify(...).called(1) counts only the second phase. reset(repository) removes the stub as well, so the second greet would call an unstubbed fetchUser, which returns null and fails with a type error because Future<User> was expected.