Sub topic 13
Common mistakes and how to read the errors
Assume you know Dart classes, Future, Stream, flutter_test, constructor injection, and the basic mocktail flow of creating a mock, stubbing a call, and verifying an interaction. This chapter focuses on failures that often look mysterious but usually point to one specific problem.
Read the error from the first failed call
A mocktail test usually fails in one of three places:
- The stub does not match the call that the production code makes.
- The mock returns an invalid value because the method was not stubbed.
- The verification does not match the interactions that actually happened.
Start with the first error message and inspect the method call shown in the stack trace. Check its method name, arguments, named arguments, and return type before changing the test.
| Error symptom | Likely cause | Usual fix |
|---|---|---|
| A non-nullable value is `null` | The call was not stubbed or the matcher did not match | Stub the exact call or use the correct matcher |
| `Bad state: No method stub was called from within \`when()\`` | The expression inside `when` did not invoke a mock method | Use `when(() => repository.fetchUser('42'))` |
| A custom argument matcher fails | Mocktail has no fallback value for that type | Register a `Fake` with `registerFallbackValue` |
| Verification reports the wrong call count | The code called the method more or fewer times than expected | Check control flow and use `called(n)` deliberately |
Unstubbed calls and mismatched stubs
Mocktail returns null for an unstubbed call. That is invalid for most non-nullable Dart return types. The resulting error may mention a Null value being used as a Future<User>, rather than clearly saying that the stub is missing.
A stub must match the real invocation. For example, a stub for '7' does not match a production call with '42'.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class User {
const User(this.name);
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(String id);
}
class MockUserRepository extends Mock implements UserRepository {}
class GreetingService {
GreetingService(this.repository);
final UserRepository repository;
Future<String> greet(String id) async {
final user = await repository.fetchUser(id);
return 'Hello, ${user.name}!';
}
}
void main() {
test('uses the matching stub', () async {
final repository = MockUserRepository();
final service = GreetingService(repository);
when(() => repository.fetchUser(any()))
.thenAnswer((_) async => const User('Ada'));
expect(await service.greet('42'), 'Hello, Ada');
verify(() => repository.fetchUser('42')).called(1);
});
}For Future and Stream methods, prefer thenAnswer. It creates the asynchronous result when the method is called. Use thenThrow when the dependency should fail:
when(() => repository.fetchUser(any()))
.thenThrow(Exception('offline'));Do not put a real method call inside when. The callback must call a method on the mock. Otherwise mocktail has no invocation to record and reports that no method stub was called.
Matchers and fallback values
Do not mix a matcher with a literal value for the same argument position in one invocation. This is invalid:
// Incorrect: the first argument is a matcher, but the second is not.
when(() => someMock.method(any(), 'fixed'));Use literals for every argument, or match every relevant argument:
when(() => someMock.method(any(), any()));any() for a custom non-nullable type, such as User, needs a fallback value. A Fake is a lightweight object used only to satisfy matcher type requirements.
class FakeUser extends Fake implements User {}
void main() {
setUpAll(() {
registerFallbackValue(FakeUser());
});
}Register the fallback once, usually in setUpAll, before using any() or captureAny() with User.
Verification and test state
verify(() => repository.fetchUser('42')).called(1) checks that exactly one matching call occurred. Use verifyNever when a call must not happen. Use verifyInOrder when sequence matters.
A fresh mock in setUp prevents one test's interactions from affecting another. clearInteractions(mock) removes recorded calls but keeps stubs. reset(mock) removes both calls and stubs, so later code must configure the mock again.
Exercise
A test uses when(() => repository.saveUser(any())) and fails because mocktail cannot create a fallback value for User. What should you add?
Show answer
Define a FakeUser extends Fake implements User and call registerFallbackValue(FakeUser()), normally inside setUpAll.