Sub topic 7
Verifying that calls happened
A stub controls what a mock returns. Verification checks what the code under test did to the mock. This chapter covers verify, call counts, verifyNever, verifyInOrder and verifyNoMoreInteractions, and how mocktail reports a failed check.
It assumes you can already create a mock class and stub methods with when. Argument capture and fallback values get their own chapters.
Why verify at all
Many methods return nothing useful. A service that writes an audit entry, sends an analytics event or saves a record has no return value to assert on. The visible result is a call on a collaborator, so you assert on the call.
Prefer asserting on return values and rendered UI when you can. Verification fits when the call is the behavior you care about. It is a poor fit when the call is an implementation detail that may change without changing behavior.
The code under test
The examples use one repository and one audit log. GreetingService records an event before and after fetching a user.
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);
}
abstract class AuditLog {
void record(String event);
}
class GreetingService {
GreetingService(this._repository, this._audit);
final UserRepository _repository;
final AuditLog _audit;
Future<String> greet(String id) async {
_audit.record('greet:start:$id');
final user = await _repository.fetchUser(id);
_audit.record('greet:done:$id');
return 'Hello, ${user.name}!';
}
}
class MockUserRepository extends Mock implements UserRepository {}
class MockAuditLog extends Mock implements AuditLog {}record returns void. mocktail lets you call an unstubbed void method, so the audit log needs no when setup. Unstubbed methods that return a Future or a non-nullable type do need a stub.
How verify works
Every call on a mock is recorded as an interaction. That includes calls you never stubbed. verify takes a closure that makes one call, then looks through the recorded interactions for a match. The closure is never executed against real code. mocktail uses it to read the method name and the arguments.
void main() {
late MockUserRepository repository;
late MockAuditLog audit;
late GreetingService service;
setUp(() {
repository = MockUserRepository();
audit = MockAuditLog();
service = GreetingService(repository, audit);
});
test('fetches the user exactly once', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
await service.greet('42');
verify(() => repository.fetchUser('42')).called(1);
});
}Three details matter here.
- Closure form. Write
verify(() => mock.method(args)). The closure form is the only form mocktail supports. - Await first.
greetis asynchronous. If you callverifybefore awaiting it, the recorded calls may not exist yet and the check fails for the wrong reason. - Default count. Without
.called(...),verifypasses if the call happened at least once. Add.called(1)when exactly one call is the requirement.
The sequence below shows who does what in a verified test.
Counting calls
called accepts either an integer or a matcher from package:matcher, which flutter_test re-exports.
test('counts calls with matchers', () async {
when(() => repository.fetchUser(any()))
.thenAnswer((_) async => const User('1', 'Ada'));
await service.greet('1');
await service.greet('2');
await service.greet('3');
verify(() => repository.fetchUser(any())).called(3);
verify(() => repository.fetchUser('2')).called(1);
verify(() => repository.fetchUser(any())).called(greaterThan(1));
});any() here works because the argument is a String. For custom types you need a fallback value, which a later chapter covers.
Each verify is independent. The check for '2' does not consume the call, so the three assertions above all pass.
Asserting that something did not happen
verifyNever passes only if no matching call was recorded. It is equivalent to verify(...).called(0) and reads better.
test('does not record completion when the fetch fails', () async {
when(() => repository.fetchUser(any())).thenThrow(Exception('offline'));
await expectLater(service.greet('42'), throwsException);
verify(() => audit.record('greet:start:42')).called(1);
verifyNever(() => audit.record('greet:done:42'));
});This test checks a behavior that no return value exposes. The service must not claim success after a failure. The expectLater line also completes the asynchronous work before the verification runs.
Checking the order of calls
verifyInOrder takes a list of closures and passes if matching calls occurred in that sequence.
test('records start before done', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
await service.greet('42');
verifyInOrder([
() => audit.record('greet:start:42'),
() => repository.fetchUser('42'),
() => audit.record('greet:done:42'),
]);
});Two properties are worth knowing.
- Interleaving is allowed. Other calls may happen between the ones you list. The check requires only that your listed calls appear in that relative order.
- Mocks can differ. The list above mixes
auditandrepository. The ordering is global across mocks, not per mock. This makes it the right tool for checking "save, then notify" sequences.
Catching unexpected calls
verifyNoMoreInteractions fails if the mock received any call that you have not verified.
test('makes no calls beyond the ones we expect', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
await service.greet('42');
verify(() => repository.fetchUser('42')).called(1);
verifyNoMoreInteractions(repository);
});A successful verify marks the matching interactions as verified. Whatever remains unmarked makes verifyNoMoreInteractions fail. Interactions made while stubbing with when are not recorded, so stubs do not count against you.
Choosing the right check
| Check | Passes when | Typical use |
|---|---|---|
| `verify(...)` | The call happened at least once | Confirm a side effect occurred |
| `verify(...).called(n)` | The call happened exactly `n` times | Guard against duplicate work |
| `verify(...).called(greaterThan(n))` | The count satisfies the matcher | Retry or polling logic |
| `verifyNever(...)` | No matching call happened | Confirm a branch was skipped |
| `verifyInOrder([...])` | The listed calls happened in that order | Sequencing, such as save then notify |
| `verifyNoMoreInteractions(mock)` | Every recorded call was verified | Strict boundaries |
Reading a failed verification
When a check fails, mocktail prints what it expected and what actually happened. Suppose the service called fetchUser('7') but the test verified '42'. The message looks like this:
No matching calls. All calls: MockUserRepository.fetchUser('7')Read it in this order.
- Check the argument values in the "All calls" list against your verify closure.
- If the list is empty, the code never reached the mock. Look for an early return, a missing
awaitin the test, or a different mock instance being injected. - If the call count is wrong, the message shows the expected and actual counts.
Common mistakes
- Verifying before awaiting. The asynchronous work has not run, so the call list is empty. Await the future or use
expectLaterfirst. - Mixing literals and matchers. In one call, use either all literal values or all matchers. The call
verify(() => mock.send('a', any()))throws a mocktail error for most signatures. Writeverify(() => mock.send(any(), any()))or use only literals. - Verifying the stub instead of the behavior.
when(...)followed byverify(...)of the same call, with no code under test between them, proves nothing about your code. - Over-verifying. Asserting every call makes tests brittle. Verify the calls that express the requirement.
Exercise
A test stubs repository.fetchUser('42'), calls service.greet('42') without await, and then runs verify(() => audit.record('greet:done:42')).called(1). The verification fails with "No matching calls". Why, and how do you fix it?
Show answer
greet suspends at its await on fetchUser, so it has not yet reached the second audit.record call when verify runs. Await the future first, either with await service.greet('42'); or await expectLater(service.greet('42'), completion('Hello, Ada!'));, so the interactions are recorded before the verification.
Exercise
Write a verification that passes only if audit.record('greet:start:42') happened before repository.fetchUser('42'), and also confirm that audit.record('greet:done:99') never happened.
Show answer
verifyInOrder([
() => audit.record('greet:start:42'),
() => repository.fetchUser('42'),
]);
verifyNever(() => audit.record('greet:done:99'));
verifyInOrder checks the relative order across both mocks, and verifyNever fails if any matching call was recorded.