Sub topic 6
Writing fakes and mocks for repositories
This chapter covers how to build test doubles for the repositories your providers depend on, and how to plug them into a ProviderContainer. It assumes you can write tests with flutter_test, know the basic Riverpod providers (Provider, FutureProvider, NotifierProvider), and are comfortable with async/await. It builds on the previous chapters: creating a container per test, reading providers, and overriding providers.
Why providers need test doubles
A provider that talks to a network, a database, or a platform plugin is hard to test as written. Tests become slow, flaky, and dependent on outside state. The usual fix has two parts:
- Put the outside access behind a small abstract class, the repository.
- Expose that repository through a provider, so a test can swap it out with an override.
A test double is any object that stands in for the real dependency during a test. Two kinds matter here:
- A fake is a working, simplified implementation. It has real behavior, such as returning stored data or throwing a configured error.
- A mock is an object generated or configured to respond to specific calls and to remember how it was called. You set expectations on it, then verify them.
Both kinds work with overrides. The difference lies in who holds the behavior: the fake's own code, or the stubs you declare in each test.
The code under test
The examples below use this code, assumed to live in lib/user_repository.dart of a package named my_app.
import 'package:flutter_riverpod/flutter_riverpod.dart';
abstract class UserRepository {
Future<String> fetchName();
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => throw UnimplementedError('Override userRepositoryProvider'),
);
final userNameProvider = FutureProvider<String>(
(ref) => ref.watch(userRepositoryProvider).fetchName(),
);The default body of userRepositoryProvider throws. This is deliberate. The app overrides it at startup with the real implementation, and a test that forgets to override it fails loudly with UnimplementedError. A test can never hit a real server by accident.
The diagram shows how an override changes the dependency chain.
Writing a hand-made fake
Implement the repository interface with implements, not extends. Using implements forces you to provide every member, so when the interface gains a method the compiler tells you which fakes need updating.
A useful fake is configurable and records what happened to it:
import 'package:my_app/user_repository.dart';
class FakeUserRepository implements UserRepository {
FakeUserRepository({this.name = 'Ada'});
String name;
Object? error;
int fetchCount = 0;
@override
Future<String> fetchName() async {
fetchCount++;
final failure = error;
if (failure != null) throw failure;
return name;
}
}The fields are public on purpose. A test can set name or error before or between reads, and can inspect fetchCount afterward. Because the method is async, a throw inside it becomes a failed Future, which matches what a real repository does.
Here is a test that uses it, including a re-fetch with a changed value:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/user_repository.dart';
ProviderContainer createContainer({List<Override> overrides = const []}) {
final container = ProviderContainer(overrides: overrides);
addTearDown(container.dispose);
return container;
}
void main() {
test('refetches after invalidation', () async {
final fake = FakeUserRepository(name: 'Ada');
final container = createContainer(
overrides: [userRepositoryProvider.overrideWithValue(fake)],
);
expect(await container.read(userNameProvider.future), 'Ada');
fake.name = 'Grace';
container.invalidate(userNameProvider);
expect(await container.read(userNameProvider.future), 'Grace');
expect(fake.fetchCount, 2);
});
}This block also needs the FakeUserRepository class from the previous block, either pasted into the same file or imported from a shared test file. The createContainer helper is the one from the earlier chapter. It registers disposal with addTearDown, so each test gets a fresh container that is cleaned up even when an assertion fails.
fetchCount proves that invalidate caused a second fetch. Without it, you could only see the changed name and could not tell whether the provider was rebuilt or the old value was reused.
Controlling timing with a Completer
An async fake returns its value in the next microtask, so a test never observes the loading state. When you need to assert on that state, give the fake a Completer and decide when it finishes:
import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/user_repository.dart';
class ManualUserRepository implements UserRepository {
final completer = Completer<String>();
@override
Future<String> fetchName() => completer.future;
}
void main() {
test('is loading until the repository completes', () async {
final repository = ManualUserRepository();
final container = ProviderContainer(
overrides: [userRepositoryProvider.overrideWithValue(repository)],
);
addTearDown(container.dispose);
expect(container.read(userNameProvider), isA<AsyncLoading<String>>());
repository.completer.complete('Ada');
expect(await container.read(userNameProvider.future), 'Ada');
});
}The first read starts the provider. The repository has not answered, so the state is AsyncLoading. Completing the Completer then lets the awaited .future resolve.
Testing the error path
You do not need a second fake class to test failures. The configurable error field already covers it:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/user_repository.dart';
void main() {
test('surfaces repository errors', () async {
final fake = FakeUserRepository()..error = Exception('offline');
final container = ProviderContainer(
overrides: [userRepositoryProvider.overrideWithValue(fake)],
);
addTearDown(container.dispose);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
});
}Use expectLater with await. A plain expect on a future does not make the test wait for it, so the test could finish before the assertion runs.
Using a mock with mocktail
A mock helps when the fake would need many switches to express each scenario, or when the thing you care about is how the repository was called. The mocktail package needs no code generation. Add it under dev_dependencies.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mocktail/mocktail.dart';
import 'package:my_app/user_repository.dart';
class MockUserRepository extends Mock implements UserRepository {}
void main() {
test('reads the name once and does nothing else', () async {
final repository = MockUserRepository();
when(() => repository.fetchName()).thenAnswer((_) async => 'Ada');
final container = ProviderContainer(
overrides: [userRepositoryProvider.overrideWithValue(repository)],
);
addTearDown(container.dispose);
expect(await container.read(userNameProvider.future), 'Ada');
verify(() => repository.fetchName()).called(1);
verifyNoMoreInteractions(repository);
});
test('mock failure through thenAnswer', () async {
final repository = MockUserRepository();
when(() => repository.fetchName())
.thenAnswer((_) async => throw Exception('offline'));
final container = ProviderContainer(
overrides: [userRepositoryProvider.overrideWithValue(repository)],
);
addTearDown(container.dispose);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
});
}The second test uses thenAnswer with an async closure rather than thenThrow. thenThrow throws synchronously when fetchName() is called, but a real repository returns a failed Future. Riverpod catches both, but the async form matches production behavior. It also avoids surprises in code that attaches .catchError to the returned future.
Mocktail returns null for any method you have not stubbed. If a method returns Future<void>, stub it with thenAnswer((_) async {}). Otherwise the call fails with a type error in the middle of your provider code.
Choosing between a fake and a mock
| Question | Fake | Mock |
|---|---|---|
| Where does behavior live? | In a class you write once | In `when(...)` stubs inside each test |
| Setup cost | One class per repository | One-line class declaration, then stubs |
| Checking how it was called | Manual counters and lists | `verify`, `verifyNever`, `called(n)` |
| Reacts to state, such as save then fetch | Yes, it can keep real state | Only if you script each answer |
| Breaks when internal call order changes | Rarely | More often, because tests assert on calls |
| Best for | Stateful repositories used by many tests | One-off scenarios and interaction checks |
A reasonable default is to write a fake for repositories that many tests share, and to reach for a mock when a single test needs to verify an interaction. The two coexist. Both are passed through overrideWithValue, so the provider code cannot tell them apart.
Common mistakes with doubles
- Forgetting the override. The default provider throws
UnimplementedError. The failure message names the provider, so check that the override list matches the provider the code actually watches. - Reusing one fake across tests. Fake state such as
fetchCountanderrorcarries over. Create the fake inside each test, or insetUp. - Verifying too much.
verifyNoMoreInteractionsis useful when extra calls are a bug, such as an accidental double fetch. Use it sparingly, because it makes tests fail when you refactor harmlessly. - Over-configured fakes. If a fake grows branching logic of its own, it needs tests too. When that happens, split it into smaller fakes or switch to a mock for those scenarios.
- Letting a stub outlive the container. Create the double before the container and pass it in, so each test owns both.
Exercise
A test overrides userRepositoryProvider with a FakeUserRepository, reads userNameProvider.future, then sets fake.name = 'Grace' and reads userNameProvider.future again. The second read still returns 'Ada'. Why, and what is the fix?
Show answer
userNameProvider is a non-auto-dispose FutureProvider, so its first result is cached in the container. Changing a field on the fake does not tell Riverpod anything changed. Call container.invalidate(userNameProvider) after changing the fake, then read again. The provider then rebuilds, calls fetchName() a second time, and returns 'Grace'.
Exercise
Why does the mock failure example use thenAnswer((_) async => throw Exception('offline')) instead of thenThrow(Exception('offline'))?
Show answer
thenThrow makes fetchName() throw synchronously, but a real repository returns a Future that fails. The async form returns a failed Future, which matches production behavior.