Sub topic 13
Common mistakes and how to read the errors
This chapter assumes you can write a mocktail test with when, verify, any() and registerFallbackValue, and that your mocks come from class MockX extends Mock implements X {}. Most mocktail failures come from a small set of causes. Once you can name the cause from the error text, fixing it takes a minute.
How a mocktail failure reaches you
A mocktail mock does not fail when you call an unstubbed method. It returns null. The failure appears later, when Dart tries to treat that null as the method's declared return type. This is why many errors look like Dart type errors, not mocktail errors.
The diagram shows a triage order for a failing mock-based test.
Mistake 1: calling a method you never stubbed
This is the most common error. The test calls a mock method, no stub applies, and you see something like this:
type 'Null' is not a subtype of type 'Future<User>'The same happens for Future<void>, String, int and every other non-nullable return type. The stack trace points at the line inside your production code that called the mock, not at your test. Read the type in the message to identify which method it was. The Future<User> above means a stub for fetchUser is missing or does not match.
There are two possible causes:
- You did not stub the method at all. This includes methods the code under test calls that you did not expect, such as a
saveUsercall afterfetchUser. - You stubbed it, but the arguments you used in
whendo not match the arguments the code actually passed.
The second cause is harder to spot, because the stub appears to be there. Check the arguments in the next sections.
Mistake 2: literal arguments that never compare equal
When you pass a literal value to when or verify, mocktail compares it with ==. A custom class without operator == compares by identity, so two objects with the same field values do not match.
The next test file reproduces this problem and shows two fixes. It also shows the difference between thenThrow and an async throw, covered below.
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);
}
class MockUserRepository extends Mock implements UserRepository {}
class FakeUser extends Fake implements User {}
void main() {
late MockUserRepository repository;
setUpAll(() {
registerFallbackValue(FakeUser());
});
setUp(() {
repository = MockUserRepository();
});
test('an unstubbed call fails with a type error', () {
expect(() => repository.fetchUser('42'), throwsA(isA<TypeError>()));
});
test('a literal argument without == does not match', () {
when(() => repository.saveUser(User('7', 'Grace')))
.thenAnswer((_) async {});
// A second User('7', 'Grace') is a different instance, so no stub applies.
expect(
() => repository.saveUser(User('7', 'Grace')),
throwsA(isA<TypeError>()),
);
});
test('a predicate matcher compares by content', () async {
final idIsSeven = isA<User>().having((u) => u.id, 'id', '7');
when(() => repository.saveUser(any(that: idIsSeven)))
.thenAnswer((_) async {});
await repository.saveUser(User('7', 'Grace'));
verify(() => repository.saveUser(any(that: idIsSeven))).called(1);
});
test('thenThrow throws at the moment of the call', () {
when(() => repository.fetchUser(any())).thenThrow(Exception('offline'));
expect(() => repository.fetchUser('1'), throwsException);
});
test('an async throw produces a failed Future', () async {
when(() => repository.fetchUser(any()))
.thenAnswer((_) async => throw Exception('offline'));
final future = repository.fetchUser('1');
await expectLater(future, throwsException);
});
}To fix the equality problem, choose one of these:
- Give the class value equality, by overriding
==andhashCodeor by using a package such asequatable. - Stub with
any(that: matcher)as in the third test. - Pass the same instance to the code under test and to the stub.
Note that two const User('7', 'Grace') expressions are canonicalized to one instance, so they match. Tests that use const in one place and a plain constructor in another behave differently for this reason.
Mistake 3: a missing fallback value
If you use any() or captureAny() for a parameter of a custom type, mocktail needs a placeholder instance of that type. Without one, the test stops with a StateError whose message says a test used any or captureAny on a parameter of type User but registerFallbackValue was not called. The message also includes a short code sample. The exact wording varies between versions, but the type name is always in it.
The fix is to register a Fake once, in setUpAll, as in the example above. Register one fallback per custom type that appears in an any() or captureAny() position. Built-in types such as String, int and bool need no registration. A mock class used as an argument needs one too, because it is also a custom type.
Mistake 4: `thenReturn` with a Future or Stream
thenReturn(Future.value(user)) is rejected with an ArgumentError that says thenReturn should not be used to return a Future, and to use thenAnswer instead. The same check applies to Streams. Mocktail rejects it because the value would be created once, when you write the stub, and then shared by every call.
// Rejected: ArgumentError
when(() => repository.fetchUser('42'))
.thenReturn(Future.value(const User('42', 'Ada')));
// Correct: a new Future for each call
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('42', 'Ada'));Mistake 5: `thenThrow` where you needed a failed Future
The last two tests above show a difference that matters in real code. thenThrow makes the mock method throw synchronously, before it returns a Future. An await inside a try block cannot tell the difference. These patterns can:
- A
.catchErroror.onErrorhandler attached to the returned Future never runs, because the exception escapes before the Future exists. - A
FutureBuilderthat callsrepository.fetchUser(...)insidebuildraises the exception during the build, so the widget never shows its error branch.
If the real method returns a failed Future, simulate that with thenAnswer((_) async => throw ...). Use thenThrow for methods that really throw synchronously.
Mistake 6: named arguments and positional matchers
For a named parameter, the matcher needs the parameter name. Write any(named: 'limit'), not any(). If you leave the name out, the matcher is not attached to that argument and the stub does not match the way you expect. The symptom is again the Null is not a subtype error from Mistake 1.
abstract class SearchApi {
Future<List<String>> search(String query, {int limit = 10});
}
class MockSearchApi extends Mock implements SearchApi {}
void stubSearch(MockSearchApi api) {
when(() => api.search(any(), limit: any(named: 'limit')))
.thenAnswer((_) async => ['result']);
}Also check optional parameters. A call that omits limit still carries the default value, 10, when it reaches the mock. A stub with limit: 5 will not match it.
Mistake 7: `when` on something that is not a mock
If the closure passed to when does not call a method on a mock, mocktail throws a StateError that says no method stub was called from within when(). It also asks whether a real method or an extension method was called. Typical causes:
- You passed the real object or a
Fakeinstead of the mock. - You stubbed an extension method or a static method. Mocks only intercept instance methods that the mocked type declares.
- The call is on a
finalfield of the mock that was not itself a mock.
Calling when on a Fake fails in the same way, because a Fake throws UnimplementedError for every member you did not override.
Mistake 8: reading a failed `verify`
Mocktail prints two kinds of verify failures. When the method was never called with matching arguments, the message says there were no matching calls and lists all calls the mock actually received. Compare that list with your verify line. A wrong argument value or a missing await in production code is usually visible there.
When the method was called, but a different number of times than you asked for, the message reads like this:
Expected: <1>
Actual: <2>
Unexpected number of callsThree other points about verification are easy to get wrong:
- Always pass a closure:
verify(() => repository.fetchUser('42')). Without the closure the call runs on the mock first and the verification has nothing to check. - Use
verifyNever(...)to assert that a call did not happen. The message for.called(0)suggests this as well. verifyNoMoreInteractions(mock)fails on any call you did not verify earlier, including calls you stubbed. Use it sparingly, because it ties the test to every detail of the implementation.
Mistake 9: state that leaks between tests
A mock created once at the top of main keeps its stubs and its recorded calls for the whole file. A test then passes or fails depending on which tests ran before it. This often shows up as a verify(...).called(1) that reports Actual: <2>, or a test that passes alone and fails in the full run.
Create the mock in setUp, so every test gets a new one:
late MockUserRepository repository;
setUp(() {
repository = MockUserRepository();
});If you must share a mock, call reset(repository) to remove stubs and recorded calls, or clearInteractions(repository) to clear only the recorded calls while keeping the stubs. Fresh objects in setUp are simpler and have fewer ways to go wrong.
Mistake 10: over-specifying the test
Not every failure is a bug in the mock setup. A test that verifies every internal call fails whenever you refactor, even when the behavior stays the same. Prefer assertions on outcomes, such as the returned value or the rendered text. Add verify only for side effects the caller depends on, such as saving data or sending a request. When a mock needs many stubs to behave like a small working component, consider a fake, covered in the previous chapter.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `type 'Null' is not a subtype of type 'Future<...>'` | Method not stubbed, or arguments did not match | Add the stub; check equality and named arguments |
| `StateError` about `registerFallbackValue` | `any()` or `captureAny()` on a custom type | `registerFallbackValue(FakeX())` in `setUpAll` |
| `ArgumentError` about `thenReturn` and Futures | `thenReturn(Future...)` | Use `thenAnswer` |
| `No method stub was called from within when()` | `when` closure did not call a mock method | Pass the mock; avoid extension and static methods |
| `Unexpected number of calls` | Call count differs | Check the code path; reset mocks in `setUp` |
| Error branch never renders | `thenThrow` used for an async method | `thenAnswer((_) async => throw ...)` |
Exercise
A test stubs when(() => repository.saveUser(User('7', 'Grace'))).thenAnswer((_) async {});. The code under test calls repository.saveUser(User('7', 'Grace')) with its own new instance, and the test fails with type 'Null' is not a subtype of type 'Future<void>'. Why does it fail, and what are two ways to fix it?
Show answer
User has no operator ==, so the two instances compare by identity and the stub does not match. The unmatched call returns null, which Dart cannot treat as Future<void>. Fix it by giving User value equality (override == and hashCode, or use equatable), or by stubbing with any(that: isA<User>().having((u) => u.id, 'id', '7')) after registering a fallback value for User.
Exercise
A FutureBuilder widget test stubs fetchUser with thenThrow(Exception('offline')), but the widget never shows its "Something went wrong" text and the test reports an exception from build. What change makes the error branch render?
Show answer
thenThrow makes fetchUser throw synchronously while build runs, so no Future with an error exists for the FutureBuilder to observe. Stub it with thenAnswer((_) async => throw Exception('offline')). The mock then returns a failed Future, snapshot.hasError becomes true, and the error text renders.