Sub topic 10
Replacing dependencies in tests
This chapter assumes you can write @riverpod functions and families, you know what a ProviderScope override does, and you can write a basic flutter_test or test case. Here you will use that knowledge to test provider code without touching the network or a database.
Why overrides make providers testable
A provider that builds its own dependencies is hard to test. If userProvider created an HTTP client inside its body, every test would need a live server.
The usual fix is to put each dependency in a provider of its own and have other providers read it with ref.watch. A test can then replace that one provider and leave the rest of the graph alone.
The override mechanism is the same one ProviderScope uses in the app. A ProviderContainer is the object that stores provider state. ProviderScope creates one for the widget tree. In a plain Dart test you create one yourself.
A small app to test
The examples use this code. The abstract class is what makes a fake possible: the provider returns the abstract type, so a test can substitute any implementation.
// lib/user_providers.dart
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'user_providers.g.dart';
class User {
const User({required this.id, required this.name});
final int id;
final String name;
}
abstract class UserRepository {
Future<User> fetchUser(int id);
}
class HttpUserRepository implements UserRepository {
@override
Future<User> fetchUser(int id) async {
// A real app would call an API here.
throw UnimplementedError('Network access is not part of this example');
}
}
@riverpod
UserRepository userRepository(Ref ref) => HttpUserRepository();
@riverpod
Future<User> user(Ref ref, int id) async {
final repository = ref.watch(userRepositoryProvider);
return repository.fetchUser(id);
}userRepositoryProvider is a Provider<UserRepository>. userProvider is a family of FutureProvider<User> instances. If you use generator 2.x, the ref parameter types are the generated UserRepositoryRef and UserRef instead of Ref.
Writing a fake
A fake is a small class that implements the same interface and returns canned data. Put it in the test folder.
// test/fake_user_repository.dart
import 'package:your_app/user_providers.dart';
class FakeUserRepository implements UserRepository {
final List<int> requestedIds = [];
@override
Future<User> fetchUser(int id) async {
requestedIds.add(id);
return User(id: id, name: 'User $id');
}
}
class FailingUserRepository implements UserRepository {
@override
Future<User> fetchUser(int id) async {
throw StateError('server unavailable');
}
}Replace your_app with your package name. FakeUserRepository records the ids it receives, so a test can check how the provider called it. FailingUserRepository lets you test the error path.
Prefer a hand-written fake to a mock library for simple cases. A fake behaves like the real thing, so tests check results instead of exact method calls.
Testing with a ProviderContainer
The following test builds a container with one override and reads a family instance.
// test/user_provider_test.dart
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/user_providers.dart';
import 'fake_user_repository.dart';
void main() {
test('loads the user from the repository', () async {
final fake = FakeUserRepository();
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWith((ref) => fake),
],
);
addTearDown(container.dispose);
final user = await container.read(userProvider(1).future);
expect(user.id, 1);
expect(user.name, 'User 1');
expect(fake.requestedIds, [1]);
});
}Four details matter here.
- Create a new container per test. Provider state lives in the container. A shared container leaks state from one test into the next.
- Dispose the container.
addTearDown(container.dispose)runs after the test, even if it fails. It cancels listeners and disposes providers. - Override the dependency, not the provider under test. The test exercises the real
userProvidercode. Only its input is replaced. - Read
.futurefor async providers.container.read(userProvider(1))returns anAsyncValue, which isAsyncLoadingat first. The.futureproperty returns aFuture<User>that you canawait.
The next diagram shows how the pieces fit together in this test.
Testing the error path
An override can make a dependency fail. A rejected future surfaces through .future as a thrown error, so you can assert on it with throwsA.
test('propagates repository errors', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWith((ref) => FailingUserRepository()),
],
);
addTearDown(container.dispose);
await expectLater(
container.read(userProvider(1).future),
throwsA(isA<StateError>()),
);
});Use expectLater with await so the test waits for the future to complete before it ends.
Auto-dispose and container.read
Generated providers are auto-dispose by default. Auto-dispose means Riverpod destroys the state once nothing listens to the provider. A bare container.read does not count as listening.
For a provider that completes in one await, this rarely matters, because the read itself keeps the provider alive until the future resolves. It matters when you read the same provider several times and expect state to persist, or when a notifier holds state between calls.
Use container.listen to hold the provider open for the length of the test.
test('keeps counter state between reads', () {
final container = ProviderContainer();
addTearDown(container.dispose);
// Keeps the auto-dispose provider alive until the container is disposed.
container.listen(counterProvider, (previous, next) {});
container.read(counterProvider.notifier).increment();
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 2);
});This test uses the Counter notifier from an earlier chapter. Without the listen call, the state could be disposed between statements, and the final read would rebuild from build() and return 0.
Overriding a notifier
A notifier provider can be replaced with a subclass that has a different build method. This is useful when a widget reads a notifier whose real build loads data.
class FixedCounter extends Counter {
@override
int build() => 10;
}
test('starts from the overridden value', () {
final container = ProviderContainer(
overrides: [
counterProvider.overrideWith(() => FixedCounter()),
],
);
addTearDown(container.dispose);
expect(container.read(counterProvider), 10);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 11);
});overrideWith on a notifier provider takes a function with no arguments that returns a new notifier. The subclass inherits increment, so the methods still run the real code. Only the initial state changes.
Overriding in widget tests
A widget test uses ProviderScope with the same overrides list, since ProviderScope creates the container for you.
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/user_providers.dart';
import 'fake_user_repository.dart';
class UserName extends ConsumerWidget {
const UserName({super.key, required this.id});
final int id;
@override
Widget build(BuildContext context, WidgetRef ref) {
final asyncUser = ref.watch(userProvider(id));
return asyncUser.when(
data: (user) => Text(user.name),
loading: () => const CircularProgressIndicator(),
error: (error, stack) => const Text('failed'),
);
}
}
void main() {
testWidgets('shows the user name', (tester) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
userRepositoryProvider.overrideWith((ref) => FakeUserRepository()),
],
child: const MaterialApp(home: Scaffold(body: UserName(id: 7))),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pump();
expect(find.text('User 7'), findsOneWidget);
});
}The first frame shows the loading state. The call to tester.pump() lets the fake's future complete and rebuilds the widget. If you need to drive the container from the test as well, ProviderScope.containerOf(tester.element(find.byType(UserName))) returns the container the scope created.
What an override replaces
An override replaces how a provider is built. It does not patch an existing value. This has several consequences.
- The override must produce the same type.
userRepositoryProviderreturnsUserRepository, so the fake must implement that type. The compiler enforces this. - Overriding applies to everything that reads the provider. Every provider that calls
ref.watch(userRepositoryProvider)in the same container sees the fake, directly or indirectly. - An override is fixed at container creation. You pass it to the
ProviderContainerorProviderScopeconstructor. To change a dependency mid-test, put the changing value behind a notifier and update that notifier. - A family override depends on the version. The reliable pattern for families is the one shown above: override the dependency that the family reads, and keep the family itself real. Check your Riverpod version's documentation before you override individual family instances.
Common mistakes in provider tests
| Symptom | Likely cause | Fix |
|---|---|---|
| Test reads `AsyncLoading` and `expect` fails | Read the provider instead of `.future` | `await container.read(p.future)` |
| State resets between reads | Auto-dispose provider has no listener | `container.listen(p, (_, __) {})` |
| One test's state appears in another | Shared container | Create a container in each test |
| Real network call during test | Overrode the wrong provider, or none | Override the repository provider that is read |
| Test finishes before a failing future | Missing `await` on `expectLater` | `await expectLater(...)` |
| Override does not compile | Generated file is stale | Run `dart run build_runner build` |
Exercises
Exercise
A test does final user = container.read(userProvider(1)); and then calls expect(user.name, 'User 1'). It fails to compile or fails at runtime. What is wrong, and what is the fix?
Show answer
container.read(userProvider(1)) returns an AsyncValue<User>, not a User, and it is AsyncLoading until the repository future completes. Read the future instead: final user = await container.read(userProvider(1).future);.
Exercise
You override userRepositoryProvider with FakeUserRepository in a ProviderContainer. Why does userProvider(5) use the fake even though the test never touches userProvider's definition?
Show answer
userProvider reads the repository through ref.watch(userRepositoryProvider). The container resolves that provider through its override list, so any provider that depends on it receives the fake.
Exercise
Write a test that checks userProvider(2) surfaces an error when the repository throws, using the classes from this chapter.
Show answer
Create a container with userRepositoryProvider.overrideWith((ref) => FailingUserRepository()), register addTearDown(container.dispose), then run await expectLater(container.read(userProvider(2).future), throwsA(isA<StateError>()));.