Sub topic 4
Stubbing Behavior with `when`
This chapter assumes you know Dart classes, Future, and basic flutter_test tests. It also assumes you have added mocktail and created a mock class. A stub is a rule that tells a mock what to return when a method is called.
Stubbing keeps a test focused on the class under test. The mock does not contact a server, read a database, or depend on the current device state.
The basic `when` pattern
Use when with a closure containing the exact mock call. Then choose a result method:
| Method | Use it when the mock should |
|---|---|
| `thenReturn` | return a synchronous value |
| `thenAnswer` | calculate or asynchronously produce a value |
| `thenThrow` | throw an error |
This example tests a service that receives a repository through its constructor:
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class User {
const User(this.name);
final String name;
}
abstract class UserRepository {
User findUser(String id);
}
class GreetingService {
GreetingService(this.repository);
final UserRepository repository;
String greet(String id) {
final user = repository.findUser(id);
return 'Hello, ${user.name}!';
}
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('uses the user returned by the repository', () {
final repository = MockUserRepository();
final service = GreetingService(repository);
when(() => repository.findUser('42'))
.thenReturn(const User('Ada'));
expect(service.greet('42'), 'Hello, Ada!');
});
}The closure passed to when must call the mock. Do not call the real repository or place the service method inside the closure. Mocktail records the invocation and connects it to the result that follows.
Returning values with `thenReturn`
thenReturn is best for a value that is already available:
when(() => repository.findUser('42'))
.thenReturn(const User('Ada'));The stub matches the argument '42'. A call with another identifier does not use this rule. An unstubbed method usually returns a default value or throws, depending on its return type and mocktail configuration. Stub every important call explicitly so the test explains its assumptions.
You can define more than one rule for different arguments:
when(() => repository.findUser('42'))
.thenReturn(const User('Ada'));
when(() => repository.findUser('7'))
.thenReturn(const User('Grace'));Computing results with `thenAnswer`
Use thenAnswer when the result depends on the invocation or when you need an asynchronous callback. The callback receives an invocation object:
when(() => repository.findUser(any())).thenAnswer((invocation) {
final id = invocation.positionalArguments.first as String;
return User('User $id');
});For a Future, make the callback asynchronous:
abstract class AsyncUserRepository {
Future<User> fetchUser(String id);
}
class MockAsyncUserRepository extends Mock
implements AsyncUserRepository {}
void main() {
test('stubs a Future', () async {
final repository = MockAsyncUserRepository();
when(() => repository.fetchUser('42'))
.thenAnswer((_) async => const User('Ada'));
final user = await repository.fetchUser('42');
expect(user.name, 'Ada');
});
}thenAnswer creates the result when the method is called. This makes it useful for values that vary by argument and for Future or Stream methods. Stream stubbing is covered in more detail in the next chapter.
Simulating failures with `thenThrow`
A dependency can fail even when the code under test is correct. Stub that failure to test error handling:
when(() => repository.findUser('offline'))
.thenThrow(Exception('server unavailable'));For a Future, throw from an asynchronous answer:
when(() => asyncRepository.fetchUser('offline'))
.thenAnswer((_) async {
throw Exception('server unavailable');
});A test can then check that the service displays an error, retries, or propagates the exception. Test the behavior your class owns rather than testing mocktail itself.
Common mistakes
- Put the call inside
when, such aswhen(() => repository.findUser('42')). - Match the method's return type. A
Future<User>stub must produce aFuture<User>. - Do not mix real calls and mock calls in one stub.
- Create a fresh mock for each test so one test's stubs cannot affect another.
- Use argument matchers consistently when you need a rule for multiple inputs. Argument matching is covered next.
Exercise
Which stubbing method should you use for Future<String> loadName(String id) when the test should return "Ada" asynchronously?
Show answer
Use when(() => repository.loadName('42')).thenAnswer((_) async => 'Ada');.