Sub topic 6
Writing Fakes and Mocks for Repositories
Assume you know Dart classes, Future, async and await, Riverpod providers, and the package:test or flutter_test APIs. This chapter focuses on replacing a repository with test-controlled code so that a provider test does not use a network, database, or file system.
A repository is a class that hides data access. For example, a user provider might ask a UserRepository for a name. In a unit test, use an override to replace the real repository provider with a fake or mock.
Fake versus mock
A fake is a small working implementation used only in tests. It usually returns predictable data.
A mock records how it was used. A test can then verify that a method was called with specific arguments. A mock does not necessarily contain realistic data-access behavior.
| Test double | Main purpose | Typical assertion |
|---|---|---|
| Fake | Return controlled results | The provider returns `Ada` |
| Mock | Record interactions | `saveUser` received the expected user |
| Stub | Provide one fixed response | The request returns an error |
A fake is often simpler and less coupled to implementation details. Use a mock when the interaction itself is part of the behavior you need to verify.
Define the repository boundary
The provider should depend on an abstract repository rather than constructing a concrete API client directly. This creates a replacement point for tests.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class UserRepository {
Future<String> fetchName();
}
final userRepositoryProvider = Provider<UserRepository>(
(ref) => throw UnimplementedError(
'Override userRepositoryProvider in this test',
),
);
final userNameProvider = FutureProvider<String>(
(ref) => ref.watch(userRepositoryProvider).fetchName(),
);
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
void main() {
test('userNameProvider reads from the fake repository', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
FakeUserRepository(),
),
],
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}The repository provider throws if production code reaches it without a configured implementation. The test supplies one with overrideWithValue. The provider under test still uses ref.watch, so its dependency graph remains unchanged.
Make a fake configurable
A fixed fake works for one case. A configurable fake lets each test choose success, failure, or returned data.
class ConfigurableUserRepository implements UserRepository {
ConfigurableUserRepository({
this.name = 'Ada',
this.error,
});
final String name;
final Object? error;
@override
Future<String> fetchName() async {
if (error != null) {
throw error!;
}
return name;
}
}
void main() {
test('provider surfaces a repository error', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
ConfigurableUserRepository(error: Exception('offline')),
),
],
);
addTearDown(container.dispose);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
});
}Reading .future waits for a FutureProvider to complete. If the repository throws, the future returned by .future completes with an error. This test checks the provider boundary without depending on timing or a widget frame.
Record interactions with a mock
A hand-written mock can record calls without adding a mocking package.
class MockUserRepository implements UserRepository {
int fetchNameCalls = 0;
@override
Future<String> fetchName() async {
fetchNameCalls++;
return 'Ada';
}
}
void main() {
test('provider calls fetchName once', () async {
final repository = MockUserRepository();
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(repository),
],
);
addTearDown(container.dispose);
expect(await container.read(userNameProvider.future), 'Ada');
expect(repository.fetchNameCalls, 1);
});
}Interaction assertions should support a meaningful contract. Avoid asserting every internal call when the returned state is enough. A call-count assertion can become fragile if Riverpod recomputes a provider for a valid reason.
Common mistakes
- Using a shared container: State and overrides can leak between tests. Create and dispose a container for each test.
- Overriding the wrong provider: Override the provider that the code calls, not an unrelated concrete repository instance.
- Forgetting to await: An assertion may run before an async provider finishes. Read
.futureor inspect the resultingAsyncValue. - Testing the real data source: A unit test should not require internet access or a configured database.
- Overusing mocks: If the result is the behavior that matters, a fake usually gives a clearer test.
Exercise
You have a FutureProvider that calls OrderRepository.fetchOrders(). Which test double should you start with when you only need the provider to return two known orders?
Show answer
Start with a fake repository that implements fetchOrders() and returns the two known orders. Use a mock only if the test also needs to verify how the repository was called.