Mocks and test doubles
suggest changeA test double is an object that stands in for a real dependency during a test. Tests use them when the real thing is slow (a database), non-deterministic (the clock, the network), has side effects (charging a credit card, sending email) or doesn't exist yet.
Doubles only work if the code under test receives its dependencies from outside instead of creating them itself. See Dependency injection for how to structure code that way.
This article covers:
- the different kinds of test doubles
- hand-written stubs, fakes and spies
- the
Fakebase class frompackage:test - mocks with
package:mocktail(no code generation) - mocks with
package:mockito(code generation) - faking HTTP with
MockClientfrompackage:http - faking time with
package:clockandpackage:fake_async
Kinds of test doubles
People often call every double a "mock", but the terms have distinct meanings:
| Kind | What it does |
|---|---|
| Dummy | Passed around to satisfy a parameter, never actually used |
| Stub | Returns canned answers to calls |
| Fake | A working but simplified implementation, e.g. an in-memory database |
| Spy | A stub that also records how it was called |
| Mock | Configured with expectations; the test verifies which calls were made |
Stubs and fakes support state-based testing: you run the code, then check the result. Mocks and spies support interaction-based testing: you check that the code called its dependencies in the right way. Interaction checks are useful when the call itself is the observable effect, such as sending an email.
The code under test
All examples test this Checkout class. It depends on three interfaces: a payment gateway, a mailer and an order repository.
// lib/shop.dart
class Order {
final String id;
final String email;
final int cents;
const Order(this.id, this.email, this.cents);
}
class PaymentDeclined implements Exception {
final String reason;
PaymentDeclined(this.reason);
@override
String toString() => 'PaymentDeclined: $reason';
}
abstract interface class PaymentGateway {
Future<String> charge(String cardToken, int cents);
Future<void> refund(String chargeId);
}
abstract interface class Mailer {
Future<void> send({
required String to,
required String subject,
required String body,
});
}
abstract interface class OrderRepository {
Future<void> save(Order order);
Future<Order?> find(String id);
}
class Checkout {
final PaymentGateway gateway;
final Mailer mailer;
final OrderRepository repo;
Checkout(this.gateway, this.mailer, this.repo);
/// Charges the card, stores the order and emails a receipt.
/// Returns the charge id.
Future<String> placeOrder(Order order, String cardToken) async {
if (order.cents <= 0) throw ArgumentError.value(order.cents, 'cents');
final chargeId = await gateway.charge(cardToken, order.cents);
try {
await repo.save(order);
} catch (_) {
await gateway.refund(chargeId); // don't keep money for a lost order
rethrow;
}
await mailer.send(
to: order.email,
subject: 'Order ${order.id} confirmed',
body: 'We charged \$${(order.cents / 100).toStringAsFixed(2)}.',
);
return chargeId;
}
}
Add the test packages used in this article as dev dependencies:
dart pub add dev:test dev:mocktail dev:mockito dev:build_runner dev:fake_async
dart pub add http clock
Hand-written doubles
Every Dart class has an implicit interface, so a double is just a class that implements the dependency. For small interfaces this is often the clearest option and needs no packages:
import 'package:myapp/shop.dart';
import 'package:test/test.dart';
// Stub: returns a canned answer, records nothing.
class StubGateway implements PaymentGateway {
@override
Future<String> charge(String cardToken, int cents) async => 'ch_1';
@override
Future<void> refund(String chargeId) async {}
}
// Fake: a working, simplified implementation.
class InMemoryRepo implements OrderRepository {
final orders = <String, Order>{};
@override
Future<void> save(Order order) async => orders[order.id] = order;
@override
Future<Order?> find(String id) async => orders[id];
}
// Spy: records how it was called so the test can check it later.
class SpyMailer implements Mailer {
final sent = <({String to, String subject})>[];
@override
Future<void> send({
required String to,
required String subject,
required String body,
}) async {
sent.add((to: to, subject: subject));
}
}
void main() {
test('places an order', () async {
final repo = InMemoryRepo();
final mailer = SpyMailer();
final checkout = Checkout(StubGateway(), mailer, repo);
final id = await checkout.placeOrder(
const Order('o1', 'ann@example.com', 1999), 'tok_visa');
expect(id, 'ch_1');
expect(await repo.find('o1'), isNotNull);
expect(mailer.sent, [
(to: 'ann@example.com', subject: 'Order o1 confirmed'),
]);
});
}
Output of dart test -r expanded:
00:00 +0: loading test/handwritten_test.dart
00:00 +0: places an order
00:00 +1: All tests passed!
The spy stores calls as records. Records have value equality, so expect can compare the whole list in one go.
The downside of hand-written doubles is that the compiler forces you to implement every member of the interface, even the ones a test never calls. For a large interface that is a lot of boilerplate.
The Fake class from package:test
package:test/fake.dart exports a Fake class whose noSuchMethod throws UnimplementedError. If you extends Fake implements SomeInterface, the compiler no longer requires you to implement every member. You override only what the test needs:
import 'package:myapp/shop.dart';
import 'package:test/fake.dart';
import 'package:test/test.dart';
// Only charge() is implemented; every other member throws.
class DecliningGateway extends Fake implements PaymentGateway {
@override
Future<String> charge(String cardToken, int cents) async =>
throw PaymentDeclined('insufficient funds');
}
class NoMailer extends Fake implements Mailer {}
class NoRepo extends Fake implements OrderRepository {}
void main() {
test('declined payment stops the checkout', () async {
final checkout = Checkout(DecliningGateway(), NoMailer(), NoRepo());
await expectLater(
checkout.placeOrder(const Order('o1', 'ann@example.com', 500), 'tok'),
throwsA(isA<PaymentDeclined>()),
);
});
test('calling an unimplemented member', () async {
final repo = NoRepo();
try {
await repo.find('o1');
} catch (e) {
print(e);
}
});
}
Output:
00:00 +0: loading test/fake_test.dart
00:00 +0: declined payment stops the checkout
00:00 +1: calling an unimplemented member
UnimplementedError: find
00:00 +2: All tests passed!
NoMailer and NoRepo act as dummies here: if Checkout touched them after a declined payment, the test would fail with UnimplementedError. That makes them a cheap way to assert "this dependency is not used".
Mocks with mocktail
package:mocktail creates mocks at runtime, with no code generation. A mock is a class that extends Mock implements SomeInterface:
class MockGateway extends Mock implements PaymentGateway {}
The API has three parts:
when(() => mock.method(args)).thenReturn(value)/.thenAnswer((invocation) => ...)/.thenThrow(error)sets up a stubverify(() => mock.method(args))checks that a call happened;.called(n)checks the count- argument matchers:
any(),any(named: 'x'),any(that: matcher),captureAny()
Calls are wrapped in a closure (() => mock.charge(...)) so mocktail can intercept them without code generation.
For methods that return a Future or Stream, use thenAnswer, so every call gets a new instance. mocktail rejects thenReturn(Future.value(x)) with "thenReturn should not be used to return a Future. Instead, use thenAnswer((_) => future)."
Here is a full test suite for Checkout:
import 'package:mocktail/mocktail.dart';
import 'package:myapp/shop.dart';
import 'package:test/test.dart';
class MockGateway extends Mock implements PaymentGateway {}
class MockMailer extends Mock implements Mailer {}
class MockRepo extends Mock implements OrderRepository {}
class FakeOrder extends Fake implements Order {}
void main() {
late MockGateway gateway;
late MockMailer mailer;
late MockRepo repo;
late Checkout checkout;
const order = Order('o1', 'ann@example.com', 1999);
setUpAll(() {
registerFallbackValue(FakeOrder());
});
setUp(() {
gateway = MockGateway();
mailer = MockMailer();
repo = MockRepo();
checkout = Checkout(gateway, mailer, repo);
when(() => gateway.charge(any(), any())).thenAnswer((_) async => 'ch_1');
when(() => gateway.refund(any())).thenAnswer((_) async {});
when(() => repo.save(any())).thenAnswer((_) async {});
when(() => mailer.send(
to: any(named: 'to'),
subject: any(named: 'subject'),
body: any(named: 'body'),
)).thenAnswer((_) async {});
});
test('charges the card and sends a receipt', () async {
final id = await checkout.placeOrder(order, 'tok_visa');
expect(id, 'ch_1');
verify(() => gateway.charge('tok_visa', 1999)).called(1);
verify(() => repo.save(order)).called(1);
verify(() => mailer.send(
to: 'ann@example.com',
subject: 'Order o1 confirmed',
body: any(named: 'body'),
)).called(1);
verifyNever(() => gateway.refund(any()));
});
test('refunds when saving fails', () async {
when(() => repo.save(any())).thenThrow(StateError('db down'));
await expectLater(
checkout.placeOrder(order, 'tok_visa'), throwsStateError);
verifyInOrder([
() => gateway.charge('tok_visa', 1999),
() => repo.save(order),
() => gateway.refund('ch_1'),
]);
verifyZeroInteractions(mailer);
});
test('captures the email body', () async {
await checkout.placeOrder(order, 'tok_visa');
final body = verify(() => mailer.send(
to: any(named: 'to'),
subject: any(named: 'subject'),
body: captureAny(named: 'body'),
)).captured.single;
print(body);
expect(body, contains(r'$19.99'));
});
test('invalid amount never reaches the gateway', () async {
await expectLater(
checkout.placeOrder(const Order('o2', 'bob@example.com', 0), 'tok'),
throwsArgumentError,
);
verifyZeroInteractions(gateway);
});
}
Output:
00:00 +0: loading test/mocktail_test.dart
00:00 +0: (setUpAll)
00:00 +0: charges the card and sends a receipt
00:00 +1: refunds when saving fails
00:00 +2: captures the email body
We charged $19.99.
00:00 +3: invalid amount never reaches the gateway
00:00 +4: (tearDownAll)
00:00 +4: All tests passed!
Things to note:
- Mocks are created in
setUp, so every test starts with fresh mocks and no recorded calls. - Common stubs go in
setUp. A test can override one by callingwhenagain: the most recent matching stub wins, as in "refunds when saving fails". verifyInOrderchecks the order of calls, across different mocks.verifyZeroInteractions(mock)asserts a mock was never touched.verifyNoMoreInteractions(mock)asserts that every call made on it has already been verified.capturedreturns the values matched bycaptureAny, in call order.
registerFallbackValue
any() has to return a value of the parameter type to satisfy null safety. mocktail knows how to produce int, String, bool and other built-in types, but not your own classes. For those you register a fallback value once, usually in setUpAll. The fallback is never inspected, so a Fake is enough, like FakeOrder above.
If you forget, the error tells you exactly what to do:
Bad state: A test tried to use `any` or `captureAny` on a parameter of type `Order`, but
registerFallbackValue was not previously called to register a fallback value for `Order`.
To fix, do:
void main() {
setUpAll(() {
registerFallbackValue(/* create a dummy instance of `Order` */);
});
}
Unstubbed calls and failed verifications
A mocktail mock returns null for any call that has no stub. For a method whose return type is non-nullable, such as Future<String>, that fails at runtime:
test('unstubbed', () async {
final gateway = MockGateway();
await gateway.charge('tok', 100);
});
type 'Null' is not a subtype of type 'Future<String>'
test\errors_test.dart 5:7 MockGateway.charge
When you see this error in a mocktail test, a when(...) is missing.
A failing verify lists the calls that actually happened, which usually points straight at the bug:
test('wrong verify', () async {
final gateway = MockGateway();
when(() => gateway.charge(any(), any())).thenAnswer((_) async => 'ch_1');
await gateway.charge('tok_visa', 100);
verify(() => gateway.charge('tok_visa', 200)).called(1);
});
No matching calls. All calls: MockGateway.charge(tok_visa, 100)
(If you called `verify(...).called(0);`, please instead use `verifyNever(...);`.)
Matching specific arguments and computing answers
Stubs can use literal values and matchers, so a mock can behave differently for different inputs. Since the last matching stub wins, register the generic stub first and the specific ones after it:
test('specific', () async {
final gateway = MockGateway();
when(() => gateway.charge(any(), any())).thenAnswer((_) async => 'ch_ok');
when(() => gateway.charge('tok_stolen', any()))
.thenThrow(PaymentDeclined('stolen card'));
when(() => gateway.charge(any(), any(that: greaterThan(100000))))
.thenThrow(PaymentDeclined('limit exceeded'));
for (final (t, c) in [('tok_visa', 500), ('tok_stolen', 500), ('tok_visa', 200000)]) {
try {
print('$t $c -> ${await gateway.charge(t, c)}');
} on PaymentDeclined catch (e) {
print('$t $c -> $e');
}
}
});
tok_visa 500 -> ch_ok
tok_stolen 500 -> PaymentDeclined: stolen card
tok_visa 200000 -> PaymentDeclined: limit exceeded
thenAnswer receives an Invocation, so the answer can depend on the arguments or on state kept in the test:
test('answer from args', () async {
final gateway = MockGateway();
var n = 0;
when(() => gateway.charge(any(), any())).thenAnswer((inv) async {
final token = inv.positionalArguments[0] as String;
final cents = inv.positionalArguments[1] as int;
return 'ch_${++n}_${token}_$cents';
});
print(await gateway.charge('tok_a', 100));
print(await gateway.charge('tok_b', 250));
});
ch_1_tok_a_100
ch_2_tok_b_250
Named arguments are in inv.namedArguments, a Map<Symbol, dynamic>, e.g. inv.namedArguments[#to].
Mocks with mockito
package:mockito is the older and official option from the Dart team. Since null safety it generates mock classes with build_runner. The generated code knows the return types, so unstubbed methods can return sensible defaults, and matchers don't need fallback values.
Annotate the test's main with the classes to mock and import the file that will be generated:
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
import 'package:myapp/shop.dart';
import 'package:test/test.dart';
import 'mockito_test.mocks.dart';
@GenerateNiceMocks([
MockSpec<PaymentGateway>(),
MockSpec<Mailer>(),
MockSpec<OrderRepository>(),
])
void main() {
test('charges and sends a receipt', () async {
final gateway = MockPaymentGateway();
final mailer = MockMailer();
final repo = MockOrderRepository();
when(gateway.charge(any, any)).thenAnswer((_) async => 'ch_9');
final checkout = Checkout(gateway, mailer, repo);
const order = Order('o1', 'ann@example.com', 1999);
expect(await checkout.placeOrder(order, 'tok_visa'), 'ch_9');
verify(gateway.charge('tok_visa', 1999)).called(1);
verify(repo.save(order)).called(1);
final subject = verify(mailer.send(
to: 'ann@example.com',
subject: captureAnyNamed('subject'),
body: anyNamed('body'),
)).captured.single;
expect(subject, 'Order o1 confirmed');
});
}
Generate the mocks, then run the tests:
dart run build_runner build
dart test test/mockito_test.dart
build_runner writes test/mockito_test.mocks.dart with classes like this one:
class MockPaymentGateway extends _i1.Mock implements _i2.PaymentGateway {
@override
_i3.Future<String> charge(String? cardToken, int? cents) =>
(super.noSuchMethod(
Invocation.method(#charge, [cardToken, cents]),
returnValue: _i3.Future<String>.value(
_i4.dummyValue<String>(
this,
Invocation.method(#charge, [cardToken, cents]),
),
),
// ...
) as _i3.Future<String>);
// ...
}
The parameters are made nullable (String? cardToken) so that any, which is null at runtime, can be passed to them. That's why mockito uses plain when(mock.method(any)) without a closure.
Differences from mocktail:
- Matchers are
any,argThat(matcher),captureAnyfor positional arguments andanyNamed('x'),argThat(matcher, named: 'x'),captureAnyNamed('x')for named ones. @GenerateNiceMocksmakes unstubbed calls return a default value (an empty string,0, a completedFuture). That's whyrepo.saveandmailer.sendneeded no stubs above.@GenerateMocksproduces strict mocks that throw on unstubbed calls instead.- You must re-run
build_runnerwhenever a mocked interface changes. Usedart run build_runner watchwhile editing.
Which one to choose is mostly taste. mocktail avoids code generation and the extra build step; mockito avoids registerFallbackValue and gives nice defaults. Don't mix them in one test file: both export Mock, when and verify.
Faking HTTP
To test code that uses package:http, you don't need a mocking library. package:http/testing.dart has MockClient, an http.Client that passes each request to a function you provide.
The code under test takes an http.Client in its constructor:
// lib/weather.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
class WeatherClient {
final http.Client _http;
WeatherClient(this._http);
Future<double> temperature(String city) async {
final uri = Uri.https('api.example.com', '/weather', {'city': city});
final res = await _http.get(uri, headers: {'Accept': 'application/json'});
if (res.statusCode != 200) {
throw http.ClientException('HTTP ${res.statusCode}', uri);
}
final json = jsonDecode(res.body) as Map<String, dynamic>;
return (json['temp'] as num).toDouble();
}
}
The test returns canned responses and records the requests:
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
import 'package:myapp/weather.dart';
import 'package:test/test.dart';
void main() {
test('parses the temperature', () async {
final requests = <http.Request>[];
final client = MockClient((request) async {
requests.add(request);
return http.Response(jsonEncode({'temp': 21.5}), 200,
headers: {'content-type': 'application/json'});
});
final weather = WeatherClient(client);
expect(await weather.temperature('Kraków'), 21.5);
final req = requests.single;
print('${req.method} ${req.url}');
print(req.headers);
});
test('throws on server error', () async {
final client = MockClient((_) async => http.Response('oops', 503));
await expectLater(
WeatherClient(client).temperature('Oslo'),
throwsA(isA<http.ClientException>()
.having((e) => e.message, 'message', 'HTTP 503')),
);
});
}
Output:
00:00 +0: loading test/http_test.dart
00:00 +0: parses the temperature
GET https://api.example.com/weather?city=Krak%C3%B3w
{Accept: application/json}
00:00 +1: throws on server error
00:00 +2: All tests passed!
MockClient is a fake in the terminology above: real http.Client behaviour with a function in place of the network. The handler can inspect request.url.path and request.method to serve several endpoints. See HTTP Request and REST APIs for the client side of this code.
Faking time
Code that calls DateTime.now() directly is hard to test: you'd have to sleep for real to see a cache entry expire. package:clock provides a global clock whose now() can be replaced in tests. Use clock.now() instead of DateTime.now() in production code:
// lib/cache.dart
import 'package:clock/clock.dart';
class TtlCache<V> {
final Duration ttl;
final _entries = <String, (V, DateTime)>{};
TtlCache(this.ttl);
void put(String key, V value) => _entries[key] = (value, clock.now());
V? get(String key) {
final entry = _entries[key];
if (entry == null) return null;
final (value, storedAt) = entry;
if (clock.now().difference(storedAt) >= ttl) {
_entries.remove(key);
return null;
}
return value;
}
}
withClock(clock, callback) runs the callback with a different clock. Clock.fixed always returns the same time.
fakeAsync from package:fake_async goes further: it runs code in a zone with fake timers and a fake clock. Calling async.elapse(duration) moves time forward instantly and fires any Timers and Future.delayed callbacks that fall due. fakeAsync also overrides clock, so the two packages work together:
import 'dart:async';
import 'package:clock/clock.dart';
import 'package:fake_async/fake_async.dart';
import 'package:myapp/cache.dart';
import 'package:test/test.dart';
void main() {
test('withClock: a fixed point in time', () {
final cache = TtlCache<String>(const Duration(minutes: 5));
final start = DateTime.utc(2026, 1, 1, 12);
withClock(Clock.fixed(start), () => cache.put('k', 'v'));
withClock(Clock.fixed(start.add(const Duration(minutes: 4))), () {
expect(cache.get('k'), 'v');
});
withClock(Clock.fixed(start.add(const Duration(minutes: 5))), () {
expect(cache.get('k'), isNull);
});
});
test('fakeAsync: timers and clock move together', () {
fakeAsync((async) {
final cache = TtlCache<int>(const Duration(seconds: 30));
cache.put('answer', 42);
var fired = false;
Timer(const Duration(minutes: 1), () => fired = true);
async.elapse(const Duration(seconds: 29));
print('after 29s: ${cache.get('answer')}, fired=$fired');
async.elapse(const Duration(seconds: 31));
print('after 60s: ${cache.get('answer')}, fired=$fired');
});
});
}
Output:
00:00 +0: loading test/time_test.dart
00:00 +0: withClock: a fixed point in time
00:00 +1: fakeAsync: timers and clock move together
after 29s: 42, fired=false
after 60s: null, fired=true
00:00 +2: All tests passed!
Both tests finish in milliseconds even though they simulate a minute. The fakeAsync callback is synchronous: don't await inside it, because fake time only moves when you call elapse or flushMicrotasks. This is a good way to test retries, timeouts and debouncing; see Cancellation and timeouts.
Tips
- Prefer fakes over mocks for data stores. An in-memory repository lets tests check results ("the order is saved") instead of calls ("
savewas called once"), so they don't break when the implementation is refactored. - Use mocks for side effects. Verifying "an email was sent to ann@example.com" or "the refund was issued" is exactly what interaction tests are for.
- Don't mock what you don't own. Wrapping a third-party SDK in a small interface of your own makes the double simple and the test independent of the SDK's API.
package:httpis an exception, since it ships its ownMockClient. - Don't mock value types. Create a real
Order,DateTimeorUri; they are cheap and have no side effects. - Verify only what matters. Over-specified tests that verify every call fail on harmless refactorings. Use
any()for arguments the test doesn't care about. - Fresh doubles per test. Create mocks in
setUp, not as top-level variables, so stubs and recorded calls don't leak between tests. - Keep interfaces small. If a class needs a mock with ten stubs to be tested, it probably does too much.
To measure how much of your code the tests actually exercise, see Code coverage. To run many similar cases against the same doubles, see Parameterized tests.