Sub topic 4
Stubbing behavior with when
This chapter assumes you can write test and setUp blocks with flutter_test. It also assumes you have a Mock subclass for an abstract class, as in the previous chapter. Here you will learn how to tell a mock what to return and when to throw. You will also see what the mock does when you tell it nothing.
What stubbing means
A mock created with class MockClock extends Mock implements Clock {} has no behavior of its own. Every method call is recorded, and every call returns null. Stubbing is the step where you teach the mock a response for a specific call.
The pattern has three parts:
when(() => mock.method(args))names the call you want to control.- A
then...method says what that call should do. - Code under test calls the mock and gets your answer.
when(() => clock.now()).thenReturn(DateTime(2026, 1, 1));The call is wrapped in a closure (() => ...). mocktail needs the closure so it can run the call in a recording mode and register it as a stub. If you wrote when(clock.now()), the call would run first and mocktail would receive its result, not the call itself. The code would not compile for most return types.
A runnable example
The example below uses a synchronous dependency, so you can focus on when without Futures. Add mocktail to dev_dependencies first.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
abstract class Clock {
DateTime now();
String get timeZoneName;
}
class GreetingPicker {
GreetingPicker(this._clock);
final Clock _clock;
String greeting() {
final hour = _clock.now().hour;
if (hour < 12) return 'Good morning';
if (hour < 18) return 'Good afternoon';
return 'Good evening';
}
}
class MockClock extends Mock implements Clock {}
void main() {
late MockClock clock;
late GreetingPicker picker;
setUp(() {
clock = MockClock();
picker = GreetingPicker(clock);
});
test('says good morning before noon', () {
when(() => clock.now()).thenReturn(DateTime(2026, 1, 1, 9));
expect(picker.greeting(), 'Good morning');
});
test('says good evening after six', () {
when(() => clock.now()).thenReturn(DateTime(2026, 1, 1, 20));
expect(picker.greeting(), 'Good evening');
});
test('getters are stubbed the same way', () {
when(() => clock.timeZoneName).thenReturn('UTC');
expect(clock.timeZoneName, 'UTC');
});
}Each test stubs only what it needs. The tests do not depend on the real time, so they give the same result at any hour of the day.
The three ways to answer
| Method | Use it for | What the call does |
|---|---|---|
| `thenReturn(value)` | Synchronous methods and getters | Returns a fixed value |
| `thenThrow(error)` | Any method | Throws the error when called |
| `thenAnswer((invocation) => ...)` | Futures, Streams, and answers computed from arguments | Runs your function and returns its result |
thenReturn
thenReturn hands back the same object on every call. If the method returns a mutable object, every caller shares that one instance. Create a new object per test if the code under test changes it.
Do not use thenReturn for methods that return a Future or Stream. mocktail rejects it with an ArgumentError that tells you to use thenAnswer. The reason is that one Future instance can be completed only once and can be awaited many times in surprising ways. thenAnswer builds a fresh one for each call. The next chapter covers this in detail.
thenThrow
thenThrow makes the mock fail the way a real dependency would.
test('reports a failure when the clock is unavailable', () {
when(() => clock.now()).thenThrow(StateError('no clock'));
expect(() => picker.greeting(), throwsStateError);
});Pass the error object, not a type. The mock throws that exact instance each time. The matcher throwsStateError is checked against a function, so the call is wrapped in a closure here too.
For methods that return a Future, thenThrow throws synchronously at the call site, before any await. A real async method usually returns a failed Future instead. To get that behavior, use thenAnswer((_) async => throw Exception('offline')). Many tests use thenThrow for async methods and still pass, but the two forms differ when the code under test attaches catchError or .then to the returned Future.
thenAnswer with the invocation
thenAnswer receives an Invocation. It exposes the arguments that the code under test passed.
abstract class Formatter {
String format(String text, {bool upper = false});
}
class MockFormatter extends Mock implements Formatter {}
void main() {
test('answers using the arguments it receives', () {
final formatter = MockFormatter();
when(() => formatter.format(any(), upper: any(named: 'upper')))
.thenAnswer((invocation) {
final text = invocation.positionalArguments.first as String;
final upper = invocation.namedArguments[#upper] as bool;
return upper ? text.toUpperCase() : text;
});
expect(formatter.format('hi', upper: true), 'HI');
expect(formatter.format('hi'), 'hi');
});
}Positional arguments are in a list. Named arguments are in a map keyed by a symbol such as #upper. Argument matchers like any() get their own chapter. Here they are used only so the stub applies to every input.
Stubbing sequences
You can chain several then... calls on one stub. The mock uses them in order, one per call. After the last one, it keeps repeating the final answer.
test('returns different values on successive calls', () {
when(() => clock.now())
.thenReturn(DateTime(2026, 1, 1, 9))
.thenReturn(DateTime(2026, 1, 1, 20));
expect(picker.greeting(), 'Good morning');
expect(picker.greeting(), 'Good evening');
expect(picker.greeting(), 'Good evening');
});This is useful for retry logic: fail twice, then succeed. Mix thenThrow and thenReturn in the same chain.
Overriding a stub
Stubs are matched from the most recent to the oldest. If you stub the same call twice, the second when replaces the first. This lets you set a default in setUp and override it in one test.
setUp(() {
clock = MockClock();
when(() => clock.now()).thenReturn(DateTime(2026, 1, 1, 9));
picker = GreetingPicker(clock);
});
test('uses the default morning time', () {
expect(picker.greeting(), 'Good morning');
});
test('a test can replace the default', () {
when(() => clock.now()).thenReturn(DateTime(2026, 1, 1, 21));
expect(picker.greeting(), 'Good evening');
});Keep defaults in setUp small. If a test depends on a stub it cannot see, it becomes hard to read.
How the mock chooses a response
The recording step matters for the later chapters on verify. The key point for now is the "no match" branch. A call with arguments that differ from the stub does not match. Stubbing fetchUser('42') does nothing for fetchUser('43').
Unstubbed calls
If you forget to stub a method, the mock returns null. When the method's return type does not allow null, Dart raises a TypeError inside the test. For example, an unstubbed Future<User> fetchUser(String id) fails with a message like this:
type 'Null' is not a subtype of type 'Future<User>' in type castThis message means "you called a method on a mock that has no stub for these arguments". Look for a missing when, or for arguments that differ from the ones you stubbed.
Methods that return void or a nullable type do not fail. An unstubbed call is recorded and returns null. For a method that returns Future<void>, you still need a stub, because the return type is a non-nullable Future:
when(() => repository.saveUser(any())).thenAnswer((_) async {});Stubbing is not verifying
A stub says how the mock responds. It does not require the code under test to make the call. If a test stubs clock.now() but the code never calls it, the test can still pass. Use verify to check that a call happened. That is the subject of a later chapter.
The reverse also holds. The call you make inside when(() => ...) is not counted as an interaction, so stubbing does not add to the numbers that verify checks.
Common mistakes with when
- Stubbing after the call. The
whenmust run before the code under test calls the mock. Put it in the test body orsetUp, ahead of the action. - Stubbing something that is not a mock.
when(() => realObject.method())fails with a message that the call was not made on a mock. Check that the object you pass to the code under test is the mock. - Using
thenReturnfor a Future. Switch tothenAnswer((_) async => value). - Mismatched arguments.
when(() => repo.fetchUser('42'))matches only'42'. Objects without==match only when they are the same instance. - Calling a mock inside another
when. Compute values first, then pass them tothenReturn. Nesting mock calls inside a stub confuses mocktail's recording.
Summary
when(() => mock.call())selects a call. The closure is required.thenReturngives a fixed value for synchronous members.thenThrowthrows an error.thenAnswercomputes the result and is the right choice for Futures and Streams.- Chained answers play in order and repeat the last one.
- A later
whenoverrides an earlier one for the same call. - An unstubbed call returns
null, which becomes aTypeErrorfor non-nullable return types.
Exercise
A GreetingService calls _repository.fetchUser(id), which returns Future<User>. A teammate writes when(() => repository.fetchUser('42')).thenReturn(const User('42', 'Ada')); and the test fails when it runs. Name the problem and write the corrected stub.
Show answer
thenReturn cannot supply a value for a method that returns a Future, and the value User is not a Future<User>. mocktail rejects it. Use thenAnswer and return a Future: when(() => repository.fetchUser('42')).thenAnswer((_) async => const User('42', 'Ada'));
Exercise
You stub clock.now() with .thenReturn(DateTime(2026, 1, 1, 9)).thenReturn(DateTime(2026, 1, 1, 20)). What does the third call to clock.now() return, and what does an fetchUser('43') call return if only fetchUser('42') was stubbed?
Show answer
The third call returns DateTime(2026, 1, 1, 20), because the last answer in a chain repeats. The fetchUser('43') call has no matching stub, so the mock returns null. For a non-nullable return type such as Future<User>, that causes a TypeError in the test.