Sub topic 7
Replacing dependencies with fakes and mocks
This chapter assumes you can write a basic unit test with test and expect, that you know Dart's async and await, and that you have read the previous chapter on dependency injection. You should be able to add a package to dev_dependencies in pubspec.yaml.
Why replace dependencies
A unit test should check one piece of logic. If that logic calls a real database, a real HTTP client or the real clock, the test becomes slow, depends on the network, and fails for reasons unrelated to the code under test.
A test double is an object that stands in for a real dependency during a test. Because you inject dependencies through constructors, you can pass a double instead of the real object. The class under test does not know the difference.
There are three kinds of double you will meet most often:
| Kind | What it does | Typical use |
|---|---|---|
| Stub | Returns canned answers | Feed data into the code under test |
| Fake | A small working implementation, such as an in-memory list | Replace a database or API with simple real behavior |
| Mock | Records calls so you can verify them | Check that the code called a dependency correctly |
The terms overlap in everyday speech. In this chapter, "mock" means an object built with the mocktail package, and "fake" means a class you write by hand.
The code under test
The examples use a small class that depends on an abstract repository. The abstract class is the seam: both the real implementation and the doubles implement it.
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}Greeter never creates a UserRepository itself. It receives one. That is what makes the replacement possible.
Writing a hand-written fake
A fake implements the same interface with simple, predictable behavior. This one keeps users in a map.
import 'package:flutter_test/flutter_test.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}
class FakeUserRepository implements UserRepository {
FakeUserRepository(this.names);
final Map<int, String> names;
@override
Future<String> fetchName(int id) async {
final name = names[id];
if (name == null) {
throw StateError('No user with id $id');
}
return name;
}
}
void main() {
test('greets a known user', () async {
final greeter = Greeter(FakeUserRepository({1: 'Ada'}));
expect(await greeter.greet(1), 'Hello, Ada!');
});
test('propagates the error for an unknown user', () async {
final greeter = Greeter(FakeUserRepository({}));
expect(greeter.greet(2), throwsStateError);
});
}The fake has real logic, so it can serve many tests. It also has a cost: you maintain it. When UserRepository gains a method, every fake must be updated or the code stops compiling.
Using mocktail
The mocktail package generates mock behavior at runtime, so it needs no code generation step. Add it as a development dependency:
flutter pub add dev:mocktailYou create a mock by extending Mock and implementing the interface. The class body stays empty.
class MockUserRepository extends Mock implements UserRepository {}A mock does nothing useful until you stub it. Stubbing means telling the mock what to return when a specific call happens.
Stubbing with when
Use when with a closure that makes the call, then choose how to answer:
thenReturn(value)returns a value for synchronous methods.thenAnswer((_) async => value)returns a value for methods that return aFutureorStream.thenThrow(error)throws when the method is called.
Use thenAnswer for futures. With thenReturn, mocktail would hand back the same Future object on every call, and for a Future.error this can produce unhandled-error warnings. thenAnswer builds a fresh future per call.
Verifying with verify
verify checks that a call happened. You can also say how many times.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('greets the user by name', () async {
final repository = MockUserRepository();
when(() => repository.fetchName(1)).thenAnswer((_) async => 'Ada');
final greeter = Greeter(repository);
expect(await greeter.greet(1), 'Hello, Ada!');
verify(() => repository.fetchName(1)).called(1);
});
}The test follows a common shape. First arrange: create the mock and stub it. Then act: call the code under test. Finally assert: check the result and verify the interaction.
Testing failures
A stubbed exception lets you test the error path, which is hard to trigger with a real service.
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
abstract class UserRepository {
Future<String> fetchName(int id);
}
class Greeter {
Greeter(this.repository);
final UserRepository repository;
Future<String> greet(int id) async {
final name = await repository.fetchName(id);
return 'Hello, $name!';
}
}
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('rethrows when the repository fails', () {
final repository = MockUserRepository();
when(() => repository.fetchName(any()))
.thenThrow(Exception('network down'));
final greeter = Greeter(repository);
expect(greeter.greet(1), throwsException);
});
}Here any() is an argument matcher. It matches any int, so the stub applies whatever id the code passes.
Argument matchers and fallback values
Stubs match arguments by equality. fetchName(1) is stubbed only for 1. Use matchers when the exact value does not matter:
any()matches any value of the parameter's type.any(that: isA<Foo>())matches values that satisfy a matcher.captureAny()matches anything and records the value, which you read back withverify(...).captured.
There is one rule that surprises many people. If you use any() for a parameter whose type is a custom class, mocktail needs a fallback value for that type. Register one once, before the tests run:
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
class Order {
Order(this.id);
final int id;
}
abstract class OrderService {
Future<void> submit(Order order);
}
class MockOrderService extends Mock implements OrderService {}
class FakeOrder extends Fake implements Order {}
void main() {
setUpAll(() {
registerFallbackValue(FakeOrder());
});
test('submit accepts any order', () async {
final service = MockOrderService();
when(() => service.submit(any())).thenAnswer((_) async {});
await service.submit(Order(7));
verify(() => service.submit(any())).called(1);
});
}Fake is a base class from flutter_test whose methods throw if called. It is a convenient way to build a fallback value. Primitive types such as int and String already have fallbacks.
Common errors
These problems account for most failures with mocks.
- Forgetting to stub. A mock method that returns a
Futureand was never stubbed returnsnull. Awaiting it then throws a type error. Stub every method the code path calls. - Using
thenReturnfor async methods. PreferthenAnswer((_) async => ...). - Mixing matchers and raw values. In one call, use either all matchers or all plain values.
when(() => repo.find(any(), 5))fails because5is not a matcher. Writeeq(5)instead. - Verifying too much. Asserting every call makes tests break when you refactor harmlessly. Verify interactions that are part of the contract, such as "the order was submitted", and check results for everything else.
- Stubbing the wrong receiver. The stub applies only to that mock instance. If the code under test creates its own dependency internally, your mock is never used. Go back to constructor injection.
- Leaking state between tests. Create mocks inside
setUpor inside the test, not at file scope, so stubs from one test do not affect another.
Choosing between fake and mock
Fakes suit stateful behavior, such as "save a user, then read it back". A mock would need a stub for each step. Mocks suit one-off checks, such as "the analytics service received exactly one event".
Putting doubles to work in a run
Run the tests from the project root with the usual commands:
flutter test
flutter test test/greeter_test.dartIf a test fails with type 'Null' is not a subtype of type 'Future<...>', a method was called on a mock without a stub. The stack trace points to the line.
Exercise
A test stubs when(() => repository.fetchName(1)).thenAnswer((_) async => 'Ada'), but the code under test calls repository.fetchName(2). What happens, and how do you make the stub apply to any id?
Show answer
The call with id 2 does not match the stub, so the mock returns null for a Future method and awaiting it throws a type error. Replace the argument with a matcher: when(() => repository.fetchName(any())).thenAnswer((_) async => 'Ada'). The any() matcher matches every int.
Exercise
You mock a method Future<void> save(Profile profile) and stub it with when(() => service.save(any())). The test fails with an error about a missing fallback value. What do you add, and where?
Show answer
Call registerFallbackValue with an instance of Profile (for example a class that extends Fake implements Profile) once, in setUpAll, before the tests that use any() for a Profile parameter.