Sub topic 5
Overriding providers to isolate the code under test
A provider usually depends on other providers: a repository, an HTTP client, a clock, a settings store. A unit test of that provider should not hit the network or the real clock. An override replaces one provider inside one ProviderContainer, so the code under test runs against a stand-in you control.
This chapter assumes you know the basics of Riverpod (Provider, FutureProvider, NotifierProvider, ref.watch) and how to create and dispose a container in a test. It also assumes you are comfortable with async/await. The examples use the Notifier API from Riverpod 2.x.
What an override does
A container resolves every provider by looking it up in a table. When you pass overrides to the constructor, the container checks that list first. If the provider you ask for appears there, the container uses the replacement. Otherwise it uses the provider's own definition.
Three properties follow from this model:
- Overrides belong to one container. Two containers in the same process do not share them, so one test cannot affect another.
- The override list is fixed when you construct the container. You cannot add one afterward. To test with different dependencies, create another container.
- Code under test does not change.
greetingProviderstill callsref.watch(userRepositoryProvider). Only the answer differs.
Overriding a Provider with a value
The simplest case is a provider that exposes a dependency. In the test below, the default userRepositoryProvider deliberately throws. This is a common design: the app overrides it at startup, and a test that forgets to override it fails with a clear message instead of reaching a real backend.
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'),
);
final greetingProvider = FutureProvider<String>((ref) async {
final name = await ref.watch(userRepositoryProvider).fetchName();
return 'Hello, $name';
});
class FakeUserRepository implements UserRepository {
FakeUserRepository(this.name);
final String name;
int calls = 0;
@override
Future<String> fetchName() async {
calls++;
return name;
}
}
void main() {
test('greetingProvider builds the greeting from the repository', () async {
final fake = FakeUserRepository('Ada');
final container = ProviderContainer(
overrides: [userRepositoryProvider.overrideWithValue(fake)],
);
addTearDown(container.dispose);
final greeting = await container.read(greetingProvider.future);
expect(greeting, 'Hello, Ada');
expect(fake.calls, 1);
});
test('forgetting the override fails loudly', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(
() => container.read(userRepositoryProvider),
throwsA(anything),
);
});
}overrideWithValue hands the container a ready-made object. Because the test keeps a reference to fake, it can also check how the provider used the dependency, here the number of calls.
The second test uses throwsA(anything) on purpose. Riverpod 2.x rethrows the original UnimplementedError. Newer major versions may wrap provider errors in another exception type. Matching loosely keeps the test valid across versions.
Overriding with a new implementation
overrideWithValue fits providers that only hold an object. For FutureProvider, NotifierProvider, and other providers that run logic, use overrideWith. It takes a replacement creation function.
This is useful when you test a dependent provider and want its upstream provider to return fixed data without running any of its real logic:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final greetingProvider = FutureProvider<String>((ref) async {
// Imagine real work here: network calls, parsing, retries.
throw StateError('The real greeting should not run in this test');
});
final shoutProvider = Provider<AsyncValue<String>>((ref) {
return ref.watch(greetingProvider).whenData((text) => text.toUpperCase());
});
void main() {
test('shoutProvider upper-cases the greeting', () async {
final container = ProviderContainer(
overrides: [
greetingProvider.overrideWith((ref) => 'Hello, test'),
],
);
addTearDown(container.dispose);
await container.read(greetingProvider.future);
expect(container.read(shoutProvider).value, 'HELLO, TEST');
});
}The first line of the test body after setup awaits the overridden future. Without it, the first read of shoutProvider would see AsyncLoading, because even a synchronous return from a FutureProvider is delivered as a future.
The override replaces everything greetingProvider does. This is right for testing shoutProvider. It is wrong for testing greetingProvider itself. If the override replaces the very provider you are testing, the test checks your fake and proves nothing about the real code.
Overriding a Notifier
To override a NotifierProvider, pass a function that returns a new notifier. A subclass that changes build is the usual way to start from a chosen state:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
final doubledProvider = Provider<int>((ref) => ref.watch(counterProvider) * 2);
class FixedCounter extends Counter {
@override
int build() => 10;
}
void main() {
test('doubledProvider follows an overridden counter', () {
final container = ProviderContainer(
overrides: [counterProvider.overrideWith(FixedCounter.new)],
);
addTearDown(container.dispose);
expect(container.read(doubledProvider), 20);
container.read(counterProvider.notifier).increment();
expect(container.read(doubledProvider), 22);
});
}FixedCounter inherits increment and only changes the starting value. The dependent provider recomputes after the increment, so the override replaces the initial state without cutting the provider out of the graph.
Choosing the right override
| Situation | Override to use |
|---|---|
| A provider that only exposes a dependency (repository, client, clock) | `overrideWithValue(fake)` |
| A `FutureProvider` or `StreamProvider` whose result you want to fix | `overrideWith((ref) => ...)` |
| A `NotifierProvider` where you need a different starting state | `overrideWith(FakeNotifier.new)` |
| A provider that the code under test only reads | Any of the above, whichever is simplest |
| The provider you are actually testing | None. Override its dependencies instead. |
A practical rule: override at the boundary. Replace the outermost dependency that touches the outside world (the repository, not the provider that calls it). That way more of your real provider logic runs in the test.
Overriding a clock or other plain dependency
Dependencies are not limited to repositories. Anything nondeterministic is a good candidate, such as the current time:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final clockProvider = Provider<DateTime Function()>((ref) => DateTime.now);
final greetingByTimeProvider = Provider<String>((ref) {
final now = ref.watch(clockProvider)();
return now.hour < 12 ? 'Good morning' : 'Good afternoon';
});
void main() {
test('morning greeting before noon', () {
final container = ProviderContainer(
overrides: [
clockProvider.overrideWithValue(() => DateTime(2026, 1, 1, 9)),
],
);
addTearDown(container.dispose);
expect(container.read(greetingByTimeProvider), 'Good morning');
});
test('afternoon greeting after noon', () {
final container = ProviderContainer(
overrides: [
clockProvider.overrideWithValue(() => DateTime(2026, 1, 1, 15)),
],
);
addTearDown(container.dispose);
expect(container.read(greetingByTimeProvider), 'Good afternoon');
});
}Each test builds its own container with its own clock. This is the main benefit of per-container overrides: the two tests can disagree about the time and never interfere.
Fakes and mocks as override values
You can pass either kind of stand-in to an override:
- A fake is a small hand-written class that implements the interface with simple behavior, like
FakeUserRepositoryabove. It is easy to read and has no extra dependencies. - A mock is generated or configured by a library such as
mocktail. It lets you stub individual calls and verify how they were called. A later chapter covers it in detail.
The override mechanism is the same for both. overrideWithValue(mockRepository) works exactly like overrideWithValue(fake).
Gotchas
- Unused overrides are silent. If you override a provider that the code under test never reads, nothing fails. The test just uses whatever the real graph does. If a test seems to ignore your fake, check that you overrode the same provider object the code reads.
- Families need care. In Riverpod 2.x you can override one instance, such as
userProvider(1).overrideWith(...), or the whole family withuserProvider.overrideWith((ref, id) => ...). Overriding one instance leaves the others real. - Override before the first read. A container builds a provider on first read and caches it. The override list is fixed at construction anyway, so build the container with the right list before you read anything.
- Fakes keep state. A fake with a mutable field, such as
calls, belongs to one test. Create it inside the test, or inside asetUp, rather than as a shared top-level variable. - Errors go through the same path. If a fake throws, the provider reports an error exactly as it would with a failing real dependency. The next chapters use this to test error states.
Exercise
Exercise
A weatherProvider is a FutureProvider<String> that calls ref.watch(weatherApiProvider).currentSummary() and returns the text. You want to test it without a network. Which provider do you override, which override method fits, and why should you not override weatherProvider itself?
Show answer
Override weatherApiProvider, the dependency that touches the network, with a fake that returns fixed text. If weatherApiProvider simply holds an object, use weatherApiProvider.overrideWithValue(FakeWeatherApi()). Create the container with that override, register addTearDown(container.dispose), then await container.read(weatherProvider.future) and assert on the text. Overriding weatherProvider itself would replace the code you want to test, so the assertion would only check your replacement.
Exercise
You override counterProvider with counterProvider.overrideWith(FixedCounter.new), but a test still reads the original starting value of 0. Name two likely causes.
Show answer
First, the container that the code reads from is not the one that received the override, for example a second ProviderContainer() was created without the override list. Second, the code under test reads a different provider object than the one you overrode, for example a similarly named provider or a different family argument. A third possibility is that FixedCounter does not actually override build.