Sub topic 15
Testing providers with ProviderContainer and overrides
This chapter shows how to test Riverpod providers without running a Flutter app. It covers plain unit tests with ProviderContainer, swapping dependencies with overrides, and widget tests with ProviderScope.
It assumes you have read the earlier chapters. You should know Notifier, AsyncNotifier, ref.watch and the repository pattern from "Structuring an app around repositories and providers". You should also know how to write a basic test and testWidgets with flutter_test.
The examples use the counterProvider, todoListProvider, todoRepositoryProvider, TodoRepository, Todo and TodoView declared in earlier chapters. Import them from your own providers file.
Why providers are easy to test
Providers live outside the widget tree. The state is held by a ProviderContainer, and ProviderScope is a widget that creates one. You can create a container yourself in a plain Dart test and read providers from it. No widgets, no pumpWidget, no device.
Each test gets its own container, so state never leaks between tests. This is the main reason Riverpod avoids global mutable singletons.
Testing a Notifier with ProviderContainer
Create the container, register its disposal, then read and act.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/providers.dart';
void main() {
test('counter increments', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(counterProvider), 0);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
}container.read is the right call here. A test has no widget to rebuild, so watch has nothing to do. addTearDown(container.dispose) runs after the test finishes and frees the provider state.
Replacing dependencies with overrides
A provider that talks to a network or database should not do so in tests. In the earlier app structure, todoRepositoryProvider throws UnimplementedError by default. A test supplies a fake through overrides.
class FakeTodoRepository implements TodoRepository {
final _items = <Todo>[const Todo(1, 'Write tests')];
@override
Future<List<Todo>> fetchAll() async => List.of(_items);
@override
Future<void> add(String title) async {
_items.add(Todo(_items.length + 1, title));
}
}
void main() {
test('todo list loads from the repository', () async {
final container = ProviderContainer(overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
]);
addTearDown(container.dispose);
final todos = await container.read(todoListProvider.future);
expect(todos.single.title, 'Write tests');
});
}TodoList.build calls ref.watch(todoRepositoryProvider). The container resolves that to the fake, so the notifier code under test is the real code. Only its dependency changed.
Which override to use
| Override | Use it when |
|---|---|
| `overrideWithValue(value)` | A plain `Provider` should return a fixed value or a fake object. |
| `overrideWith(create)` | You need to supply a new body. For a `NotifierProvider` you pass a function returning a notifier, such as `FakeCounter.new`. |
Overriding a notifier is useful when a widget test needs a known starting state:
class FakeCounter extends Counter {
@override
int build() => 41;
}
void main() {
test('starts from the overridden value', () {
final container = ProviderContainer(overrides: [
counterProvider.overrideWith(FakeCounter.new),
]);
addTearDown(container.dispose);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 42);
});
}The fake extends the real Counter, so increment still works. Only build changes.
Testing mutations on an AsyncNotifier
TodoList.add writes through the repository, invalidates itself, and awaits the new future. A test can check the whole round trip.
test('add refreshes the list', () async {
final container = ProviderContainer(overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
]);
addTearDown(container.dispose);
await container.read(todoListProvider.future);
await container.read(todoListProvider.notifier).add('Ship it');
final items = container.read(todoListProvider).requireValue;
expect(items.map((t) => t.title), ['Write tests', 'Ship it']);
});Await todoListProvider.future before asserting. Reading the provider only starts the work. The future completes when the data arrives. Reading requireValue before that point throws a StateError.
Testing the error path
A fake can fail on purpose. This is the easiest way to check that the error state is reachable.
class FailingTodoRepository implements TodoRepository {
@override
Future<List<Todo>> fetchAll() async => throw Exception('offline');
@override
Future<void> add(String title) async {}
}
test('load failure becomes an AsyncError', () async {
final container = ProviderContainer(overrides: [
todoRepositoryProvider.overrideWithValue(FailingTodoRepository()),
]);
addTearDown(container.dispose);
await expectLater(
container.read(todoListProvider.future),
throwsException,
);
expect(container.read(todoListProvider).hasError, isTrue);
});Observing every state change with container.listen
Assertions on the final state can hide a bad intermediate state. container.listen records every change. It also keeps an autoDispose provider alive.
test('counter emits each value', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final seen = <int>[];
container.listen<int>(
counterProvider,
(previous, next) => seen.add(next),
);
final notifier = container.read(counterProvider.notifier);
notifier.increment();
notifier.increment();
expect(seen, [1, 2]);
});Widget tests with ProviderScope overrides
For widget tests, wrap the widget in a ProviderScope and pass the same overrides list. The widget does not know it is under test.
testWidgets('TodoView shows loaded todos', (tester) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
],
child: const MaterialApp(home: Scaffold(body: TodoView())),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
await tester.pumpAndSettle();
expect(find.text('Write tests'), findsOneWidget);
});The first frame shows the loading branch of AsyncValue.when. pumpAndSettle lets the fake's future complete and the widget rebuild with data. Testing both frames covers two of the three when branches. A test with FailingTodoRepository covers the third.
Common mistakes
- Sharing one container across tests. State from one test then affects the next. Create a container per test.
- Forgetting to dispose. Providers that hold timers or streams keep running. Always register
addTearDown. - Asserting before the future completes. Await
provider.futurefor async providers. - Leaving the default repository in place. The
UnimplementedErrorintodoRepositoryProvideris a deliberate guard. If a test fails with it, you forgot an override. - Mocking the notifier when you could mock its dependency. Override the repository first. It exercises more real code and breaks less when the notifier changes.
Exercise
A test for todoListProvider reads it with container.read(todoListProvider) and immediately calls .requireValue. It throws a StateError. What is wrong, and how do you fix it?
Show answer
The provider has only just started loading, so its state is still AsyncLoading and has no value yet. Await the data first with await container.read(todoListProvider.future), then read requireValue or the state.
Exercise
You want a widget test where TodoView shows the error message. Which override do you pass to ProviderScope, and which provider do you override?
Show answer
Override todoRepositoryProvider with a repository whose fetchAll throws, for example todoRepositoryProvider.overrideWithValue(FailingTodoRepository()). Pump the widget, call pumpAndSettle, and expect to find the error text.