Sub topic 8
Registering fallback values for custom types
This chapter assumes you can write a basic mocktail stub with when, and that you know how any() and verify work from the previous chapters. You should also be comfortable with setUpAll and setUp from flutter_test.
Using any() or captureAny() with one of your own classes can fail with a StateError before your test body runs. This chapter explains why, how to fix it with registerFallbackValue, and where the registration belongs.
Why `any()` needs a placeholder
A stub such as when(() => repository.saveUser(any())) looks like a description, but Dart runs it as ordinary code. mocktail calls your closure once, with the mock in a recording mode. The call to saveUser happens for real, so Dart needs an actual User to pass as the argument. Dart's type system will not accept null or an arbitrary object there.
any() solves two problems at once. It registers a "match anything" matcher with mocktail. It also has to return something that is a valid User so the call type-checks. mocktail cannot build a User for you, because it does not know your constructors. You supply that placeholder with registerFallbackValue.
The placeholder is never used as test data. It only exists while mocktail records the stub or verification. Your code under test never sees it.
Seeing the error first
The following test fails on purpose. It uses any() for a User argument without registering anything.
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<void> saveUser(User user);
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('fails: no fallback value registered', () {
final repository = MockUserRepository();
when(() => repository.saveUser(any())).thenAnswer((_) async {});
});
}The test throws a StateError. Its message says a test used any or captureAny on a not-yet-registered custom type (here User) and shows a registerFallbackValue snippet to copy. Read the type name in the message, because it tells you which class needs registering.
Registering a fallback with a Fake
The usual fix is a Fake. Fake comes from package:mocktail. It is a base class whose members throw UnimplementedError when called. A fake that implements User is a valid User as far as the type system goes, and you do not have to write any of its members.
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<void> saveUser(User user);
}
class MockUserRepository extends Mock implements UserRepository {}
class FakeUser extends Fake implements User {}
void main() {
late MockUserRepository repository;
setUpAll(() {
registerFallbackValue(FakeUser());
});
setUp(() {
repository = MockUserRepository();
});
test('accepts any user once a fallback is registered', () async {
when(() => repository.saveUser(any())).thenAnswer((_) async {});
await repository.saveUser(const User('7', 'Grace'));
verify(() => repository.saveUser(any())).called(1);
});
}Because the class is implements User and not extends User, FakeUser does not need to call a User constructor. That keeps it working when the real class has required constructor arguments, private constructors, or many fields.
If the real class is simple, you can register a real instance instead:
registerFallbackValue(const User('', ''));A real instance is fine when it is cheap to build and has no side effects in its constructor. A Fake is safer when construction is awkward, and it makes mistakes loud: if your code ever touched the placeholder, you would get an UnimplementedError and not silently wrong data.
Where to register
Register in setUpAll, not in setUp. The registration is global state kept by mocktail, and it survives from one test to the next within the same test file. Registering again before every test does no harm, but it is wasted work and suggests the value belongs to a single test when it does not.
Each test file runs in its own isolate, so registrations do not carry over between files. Every file that uses any() or captureAny() with a custom type has to register that type itself. When many files need the same fallbacks, put the registrations in one helper:
import 'package:mocktail/mocktail.dart';
enum Role { admin, member }
class User {
const User(this.id, this.name);
final String id;
final String name;
}
class FakeUser extends Fake implements User {}
void registerAppFallbacks() {
registerFallbackValue(FakeUser());
registerFallbackValue(Role.member);
}Each test file then calls setUpAll(registerAppFallbacks);.
The helper also registers an enum value. Enums are custom types too, so any() for a Role parameter needs a fallback. You cannot write a Fake for an enum, because enums cannot be implemented. Register any one of its values instead.
Which matchers need a fallback
Only matchers that must produce a value of your type need one. Matching by a literal value does not.
| Matcher in a stub or verify | Needs a fallback for a custom type? |
|---|---|
| `repository.fetchUser('42')` (literal String) | No |
| `repository.saveUser(someUser)` (literal object) | No |
| `repository.saveUser(any())` | Yes |
| `repository.saveUser(captureAny())` | Yes |
| `repository.fetchUser(any())` where the parameter is `String` | No, core types such as `String`, `int` and `bool` already work |
| `any(named: 'user')` for a named parameter of a custom type | Yes |
Named arguments follow the same rule as positional ones. The named: string only says which parameter to match. The type of that parameter decides whether a fallback is required.
Capturing needs the fallback too
captureAny() is any() that also stores each argument. It returns a placeholder in the same way, so it has the same requirement. After the registration above, you can capture what the mock received:
test('captures the saved user', () async {
when(() => repository.saveUser(any())).thenAnswer((_) async {});
await repository.saveUser(const User('7', 'Grace'));
final saved = verify(() => repository.saveUser(captureAny()))
.captured
.single as User;
expect(saved.name, 'Grace');
});captured is a list with one entry per call, and each entry is the real argument from the call. The FakeUser placeholder is never in that list.
Matching by literal value: the equality trap
A literal argument in a stub is compared with ==. Plain Dart classes use identity equality, so two separately built User objects with the same fields are not equal:
when(() => repository.saveUser(User('7', 'Grace')))
.thenAnswer((_) async {});
// The service builds its own User('7', 'Grace'), which is a different object.
await repository.saveUser(User('7', 'Grace')); // does not match the stubHere the second call falls through to an unstubbed method. mocktail returns null, and Dart then throws a TypeError saying Null is not a subtype of Future<void>. That error looks unrelated to matching, which makes it easy to misdiagnose.
There are three fixes, and you can choose by what the test cares about:
- Give the class value equality, by overriding
==andhashCodeor by using a package such asequatable. This is the best option if the class is a value object in production too. - Use
constconstructors in both places. Identicalconstobjects are the same instance, but this breaks as soon as the code under test builds the object at run time. - Use
any()and register a fallback, then check the details withcaptureAny(). Use this when you care about a few fields and not the whole object.
Common mistakes
- Registering
FakeUserin one test file and expecting it to apply in another. Each file has its own isolate, so each file must register. - Calling
registerFallbackValueinside a test after thewhen(...)that needs it. The registration must run first, so usesetUpAll. - Forgetting a second type. A method that takes a
Userand aRoleneeds two registrations, and the error names only the type it hit first. After fixing one error, the next run may name another type. - Writing
class FakeUser extends Userand then having to satisfy theUserconstructor. Preferextends Fake implements User. - Using the fake as test data, for example passing
FakeUser()into the service. Any field access throwsUnimplementedError. Build a realUserfor data.
Exercise
A test calls when(() => repository.watchUsers(role: any(named: 'role'))), where role is a named parameter of the enum type Role, and it fails with a StateError naming Role. Which line fixes it, and where should it go?
Show answer
Register any value of the enum, for example registerFallbackValue(Role.member);, inside setUpAll. An enum cannot be faked with extends Fake implements Role, so a real enum value is the fallback. The named parameter does not change the rule, because the parameter type decides whether a fallback is required.
Exercise
You write when(() => repository.saveUser(User('1', 'Ada'))).thenAnswer((_) async {});. The service under test calls saveUser with its own User('1', 'Ada'), and the test fails with a TypeError about Null and Future<void>. Why, and name two ways to fix it.
Show answer
User has no value equality, so the service's object is not == to the one in the stub. The call matches no stub, mocktail returns null, and Dart rejects null as a Future<void>. Fix it by adding == and hashCode to User (or using equatable), or by stubbing with any() after registerFallbackValue(FakeUser()) and checking fields through captureAny().