Sub topic 9
Capturing arguments to inspect them
This chapter covers how to read the exact arguments a mock received, so you can assert on objects your code builds internally. It assumes you can already stub with when, verify with verify, and register fallback values with registerFallbackValue. Those topics are covered in earlier chapters.
When a matcher is not enough
Suppose ProfileService.rename fetches a user, builds a new User with a trimmed name, and saves it. The test never creates that new User, so it cannot pass one as a literal to verify.
Even if it could, User does not override ==. Two User('42', 'Ada') instances are different objects, so verify(() => repository.saveUser(User('42', 'Ada'))) fails.
You have three options:
- Give
Uservalue equality. This is a reasonable change, but it changes production code to suit a test. - Use
any(). This proves the call happened but says nothing about the contents. - Capture the argument and assert on its fields.
Capturing keeps the production code unchanged. A failed assertion also names the exact field that differed, such as name, instead of reporting only that no matching call was found.
How captureAny works
captureAny() is a matcher that accepts any value and records it. Use it inside verify. The recorded values are available from the captured list on the result.
A complete example
This file builds on the User and UserRepository types from earlier chapters. It adds a small Analytics interface, which the later sections use to show named arguments.
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);
}
abstract class Analytics {
void track(String event, {String? source});
}
class ProfileService {
ProfileService(this._repository, this._analytics);
final UserRepository _repository;
final Analytics _analytics;
Future<void> rename(String id, String newName) async {
final current = await _repository.fetchUser(id);
await _repository.saveUser(User(current.id, newName.trim()));
_analytics.track('profile_renamed', source: 'settings');
}
}
class MockUserRepository extends Mock implements UserRepository {}
class MockAnalytics extends Mock implements Analytics {}
class FakeUser extends Fake implements User {}
void main() {
late MockUserRepository repository;
late MockAnalytics analytics;
late ProfileService service;
setUpAll(() {
registerFallbackValue(FakeUser());
});
setUp(() {
repository = MockUserRepository();
analytics = MockAnalytics();
service = ProfileService(repository, analytics);
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
when(() => repository.saveUser(any())).thenAnswer((_) async {});
});
test('saves the trimmed name', () async {
await service.rename('42', ' Ada Lovelace ');
final saved = verify(() => repository.saveUser(captureAny()))
.captured
.single as User;
expect(saved.id, '42');
expect(saved.name, 'Ada Lovelace');
});
test('captures every call in order', () async {
await service.rename('42', 'First');
await service.rename('42', 'Second');
final names = verify(() => repository.saveUser(captureAny()))
.captured
.cast<User>()
.map((u) => u.name)
.toList();
expect(names, ['First', 'Second']);
});
test('captures positional and named arguments together', () {
analytics.track('opened', source: 'menu');
final captured = verify(
() => analytics.track(captureAny(), source: captureAny(named: 'source')),
).captured;
expect(captured, ['opened', 'menu']);
});
}Run it with flutter test. The next sections explain what each test relies on.
What the captured list contains
captured is a List<dynamic>. A few rules decide what ends up in it.
- It covers every matching call. If
saveUserran twice,capturedhas two entries, in call order. Use.singlewhen you expect exactly one. It throws aStateErrorif there are zero or several, which doubles as a call-count check. - It is flattened across arguments. With two
captureAnymatchers in one call, each call adds two entries. The second test above shows one entry per call. The third shows['opened', 'menu']. For two calls totrack, you would get[event1, source1, event2, source2]. - It is untyped. Cast the single value with
as User, or the whole list with.cast<User>(). Without the cast,.map((u) => u.name)fails to compile becauseuisdynamic. - Named parameters need
named:. WritecaptureAny(named: 'source'). Without the name, mocktail cannot tell which parameter the matcher belongs to.any(named: ...)follows the same rule. - Literals and matchers can be mixed.
track('opened', source: captureAny(named: 'source'))is valid. Only the matchedsourceis captured, and the literal'opened'is compared with equality.
Fallback values for custom types
captureAny() has to return something of the parameter's type while the verify closure runs. For String, int, double, bool and nullable types, mocktail handles this. For a non-nullable custom type such as User, you must call registerFallbackValue first, using a Fake like FakeUser. Do this once in setUpAll.
Without it, the test fails with an error saying that a fallback value for the type User must be registered. The fallback value is never seen by your code. It only satisfies the type system while mocktail records matchers.
Capturing only some calls with captureThat
captureThat combines a matcher with a capture. A call is matched and captured only if its argument satisfies the matcher.
test('captures only the saves for user 42', () async {
await service.rename('42', 'Ada L.');
final captured = verify(
() => repository.saveUser(
captureThat(isA<User>().having((u) => u.id, 'id', '42')),
),
).captured;
expect(captured, hasLength(1));
});Add this test inside main in the file above. It is useful when the same method is called with different kinds of arguments and you only care about one kind.
Inspecting arguments as they arrive
You can also read arguments at call time. A thenAnswer callback receives an Invocation, which exposes positionalArguments and namedArguments.
test('records names inside the stub', () async {
final names = <String>[];
when(() => repository.saveUser(any())).thenAnswer((invocation) async {
final user = invocation.positionalArguments.first as User;
names.add(user.name);
});
await service.rename('42', 'Ada L.');
expect(names, ['Ada L.']);
});This when replaces the one from setUp for this test only, because the most recent matching stub wins. It suits cases where the stub's return value depends on the argument, for example returning a different User per id. For plain assertions, verify with captureAny keeps the test more readable. The check happens after the action, in the usual arrange, act, assert order.
Choosing the right tool
| Tool | Use it when | What a failure tells you |
|---|---|---|
| Literal value in `verify` | The argument has value equality and you know it up front | No matching call was found, with a list of actual calls |
| `any()` | You only care that a call happened | Same as above |
| `argThat(matcher)` | One condition decides whether the call counts | No matching call was found |
| `captureAny()` | You want several assertions on the argument, or it has no `==` | The failing `expect` names the field and values |
| `captureThat(matcher)` | You need both filtering and inspection | The failing `expect`, or no matching call if the filter excluded everything |
| `thenAnswer` with `invocation` | The stub's behavior depends on the argument | Whatever your own code reports |
Gotchas
- Captured objects are live references. If the code under test mutates the object after the call, your assertions see the mutated state, not the state at call time. This applies to mutable lists, maps and classes with non-final fields. If it matters, copy the value inside a
thenAnswercallback. verifyfails first if nothing matched. If no call matches,verifythrows before you can readcaptured, so an emptycapturedlist is never returned.capturedandcalledcannot be chained.called(1)returns nothing. To check count and contents, keepverify(...)in a variable and readcaptured, then assert oncaptured.lengthor use.single.- Capture belongs in
verify. UsecaptureAnyinverify, not inwhen. Stubbing decides what a call returns. Verification is where recorded interactions are inspected. - Verification is repeatable. Calling
verifytwice with the same matcher works. The second call returns the same captured values. - Order matters across calls, not across mocks.
capturedpreserves the order of calls to one method. It says nothing about the order of calls between different mocks. UseverifyInOrderfor that.
Exercises
Exercise
A test calls service.rename('42', 'A') and then service.rename('42', 'B'). It runs verify(() => analytics.track(captureAny(), source: captureAny(named: 'source'))).captured. What does the list contain, and why?
Show answer
['profile_renamed', 'settings', 'profile_renamed', 'settings']. Each call to track adds one entry per captureAny, so each call adds two entries (event, then source). The entries are flattened into one list in call order.
Exercise
Your test does verify(() => repository.saveUser(captureAny())) and the run fails with a message about a missing fallback value for User. What is the fix, and where should it go?
Show answer
Declare class FakeUser extends Fake implements User {} and call registerFallbackValue(FakeUser()); once, in setUpAll. Mocktail needs a value of the parameter's type while it records the matcher. Nothing in your production code uses it.
Exercise
A test captures a List<String> passed to a mock, and the code under test later calls clear() on that same list. Why might the test see an empty list, and how can you avoid it?
Show answer
The captured value is the same object reference the code passed, not a copy. After clear(), it is empty. To preserve the state at call time, copy the argument inside a thenAnswer callback, for example seen.add(List.of(invocation.positionalArguments.first as List<String>)).