Sub topic 2
Stubbing return values
This chapter assumes you can write Dart classes and tests with package:test, and that you know what a Future is. You have added mocktail to dev_dependencies and created a mock class as shown in the previous chapter.
A stub is a fake response you set up for a mock. When your code calls a stubbed method, the mock returns the value you chose instead of running real logic. Stubs let a test control what a dependency returns, so the test checks only the code under test.
Stubbing a synchronous return value
Use when to describe the call, then thenReturn to give the result:
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
abstract class UserRepository {
String getName(int id);
Future<String> fetchName(int id);
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('returns the stubbed name', () {
final repo = MockUserRepository();
when(() => repo.getName(1)).thenReturn('Ada');
expect(repo.getName(1), 'Ada');
});
}A call with arguments that have no matching stub throws an error. Stub each argument combination your test uses.
Stubbing async methods
For a method that returns a Future, use thenAnswer and return a future from the callback:
test('returns the stubbed async name', () async {
final repo = MockUserRepository();
when(() => repo.fetchName(1)).thenAnswer((_) async => 'Grace');
expect(await repo.fetchName(1), 'Grace');
});The callback runs each time the method is called, so each call gets a fresh result.
Matching arguments
Use any() when the exact argument does not matter:
test('matches any id', () {
final repo = MockUserRepository();
when(() => repo.getName(any())).thenReturn('Anyone');
expect(repo.getName(99), 'Anyone');
});Exercise
A test stubs repo.getName(1) and then calls repo.getName(2). What happens, and how do you fix it?
Show answer
The call has no matching stub, so mocktail throws an error. Add a stub for getName(2), or use any() in the stub if the id does not matter.