Sub topic 6
Matching Arguments with any and Literal Values
This chapter explains how a mocktail stub decides whether an incoming call matches. It assumes you can write a mock class with extends Mock implements ..., stub a method with when(...), and run tests with flutter_test. Stubbing basics and Futures were covered in earlier chapters. Here you will learn the two main ways to describe arguments, literal values and any(), and how they combine with named parameters.
How a call is matched
A stub is a rule: "when this method is called with arguments that look like this, answer like that." The part inside when(() => ...) is the description. Each argument in it is either a literal value or a matcher such as any(). When the code under test calls the mock, mocktail goes through the stubs, newest first, and uses the first one whose description fits.
The last two nodes cause the most confusion. An unmatched call does not fail with a helpful message. The mock returns null, and Dart then complains that null is not a Future<User> or a double. Many "mysterious" mocktail errors are matching problems.
The setup used in this chapter
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<List<User>> search(
String query, {
int limit = 10,
bool activeOnly = true,
});
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
late MockUserRepository repository;
setUp(() {
repository = MockUserRepository();
});
test('a literal value matches only equal arguments', () async {
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
final user = await repository.fetchUser('42');
expect(user.name, 'Ada');
// No stub matches '99', so the mock returns null and Dart throws.
expect(() => repository.fetchUser('99'), throwsA(isA<Error>()));
});
test('any() matches every value of that type', () async {
when(() => repository.fetchUser(any())).thenAnswer((invocation) async {
final id = invocation.positionalArguments.first as String;
return User(id, 'User $id');
});
expect((await repository.fetchUser('1')).name, 'User 1');
expect((await repository.fetchUser('2')).name, 'User 2');
});
test('named arguments use any(named: ...)', () async {
when(
() => repository.search(
any(),
limit: any(named: 'limit'),
activeOnly: any(named: 'activeOnly'),
),
).thenAnswer((_) async => const [User('1', 'Ada')]);
final result = await repository.search('ada', limit: 5, activeOnly: false);
expect(result, hasLength(1));
});
}Literal values
When you write fetchUser('42') inside when, mocktail wraps '42' in an equality check. The stub matches any call whose argument is == to '42'.
This works well for strings, numbers, booleans, enums and const values. For your own classes, it depends on how == is defined. A class without an == override compares by identity, so a new instance never equals the one in the stub:
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class Point {
Point(this.x, this.y);
final int x;
final int y;
}
abstract class Geometry {
double distanceFromOrigin(Point point);
}
class MockGeometry extends Mock implements Geometry {}
void main() {
test('classes without == only match the same instance', () {
final geometry = MockGeometry();
final point = Point(3, 4);
when(() => geometry.distanceFromOrigin(point)).thenReturn(5);
expect(geometry.distanceFromOrigin(point), 5);
expect(
() => geometry.distanceFromOrigin(Point(3, 4)),
throwsA(isA<Error>()),
);
});
}There are three ways out. Override == and hashCode on the class, use a package such as equatable, or use any() and check the details later with verify or captureAny. Value equality on data classes is usually the best choice, because your production code benefits from it too.
any()
any() matches every value of the type the parameter expects. The type is inferred from the parameter, so any() in fetchUser(any()) means any<String>().
Use any() when the argument is not what the test is about. If a test checks how a service formats a greeting, the exact ID passed to the repository is noise, and a literal would make the test brittle.
Literals and matchers can be mixed in one call:
when(() => repository.search('ada', limit: any(named: 'limit')))
.thenAnswer((_) async => const [User('1', 'Ada')]);Use a literal where the value matters and any() where it does not.
Narrowing any with that
any() accepts a that: parameter that takes a standard matcher from flutter_test. This accepts a range of values without enumerating them:
when(() => repository.fetchUser(any(that: startsWith('admin-'))))
.thenAnswer((_) async => const User('admin-1', 'Root'));Calls with IDs that do not start with admin- are not matched by this stub.
Named arguments
Named parameters have their own rule. A matcher in a named position must say which parameter it belongs to: limit: any(named: 'limit'). The string must be the exact parameter name, including case. A mismatch or a missing named: produces an error about an argument matcher being used incorrectly.
Defaults need attention. The mock sees only the arguments the caller wrote. If the stub is search(any()) and the code calls search('ada', limit: 5), the stub says "no named arguments" while the call has one, so it does not match. Two approaches avoid this:
- Make the stub's shape the same as the call's shape. Match every named parameter the code under test passes, using
any(named: ...)or a literal. - Pass all parameters explicitly in production code, so the call shape is stable.
Order of stubs
If several stubs match one call, the most recently registered stub wins. Register the general rule first and the exceptions after it:
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);
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('later stubs override earlier ones', () async {
final repository = MockUserRepository();
when(() => repository.fetchUser(any()))
.thenAnswer((_) => Future.error(Exception('not found')));
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));
expect((await repository.fetchUser('42')).name, 'Ada');
await expectLater(repository.fetchUser('7'), throwsException);
});
}If you reverse the two when calls, any() wins for every call, including '42', and the specific stub never runs.
Matchers in verify
The same syntax works in verify. Use verify(() => repository.fetchUser(any())).called(2) to count calls regardless of ID, or a literal to check one particular call. The next chapter covers verification in detail.
Custom types and fallback values
any() works out of the box for common core types such as String, int and bool. For your own classes, such as User in saveUser(any()), mocktail needs a sample instance to use internally. Without one, you get an error asking you to call registerFallbackValue. A later chapter covers it.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `type 'Null' is not a subtype of type 'Future<User>'` | No stub matched the call | Compare stub arguments with the real call. Check literals, named arguments and the stub order. |
| Stub for `'42'` is not used for `'042'` | Literal equality is exact | Use `any(that: ...)` or normalise the input. |
| Stub with a custom class never matches | Class has no `==` | Override `==` and `hashCode`, or use `equatable`. |
| Error about a matcher used incorrectly | Named parameter without `named:` | Write `limit: any(named: 'limit')`. |
| Error asking for `registerFallbackValue` | `any()` on a custom non-nullable type | Register a fallback value, as shown in a later chapter. |
| General stub overrides a specific one | Stubs registered in the wrong order | Register the general stub first. |
| `any()` used outside `when`, `verify` or `captureAny` | Matchers only work inside these calls | Move the matcher into the `when` or `verify` closure. |
Exercises
Exercise
A service calls repository.search('dart', limit: 3). Your stub is when(() => repository.search(any())).thenAnswer((_) async => const []);. The mock returns null and the test throws a TypeError. Why, and how do you fix the stub?
Show answer
The stub describes a call with no named arguments, but the real call passes limit. The shapes differ, so no stub matches. Fix it by matching the named parameter: when(() => repository.search(any(), limit: any(named: 'limit'))). If the code also passes activeOnly, add activeOnly: any(named: 'activeOnly') as well.
Exercise
You register when(() => repository.fetchUser('42')) to return Ada, and then when(() => repository.fetchUser(any())) to return an error. What does fetchUser('42') do, and how do you get Ada for '42' and an error for everything else?
Show answer
It returns the error, because the later any() stub is newest and matches first. Swap the order: register the any() stub first, then the '42' stub.