Sub topic 11
Reusing Overrides in Widget Tests
Earlier chapters tested providers in plain Dart with a ProviderContainer. This chapter applies the same overrides to widget tests. You will wrap a widget in a ProviderScope, give it fake dependencies, and check what appears on screen.
This chapter assumes you can write testWidgets tests with pumpWidget, find, and pump. It also assumes you know ConsumerWidget, ref.watch, and the UserRepository and Counter providers from earlier in this tutorial.
Container tests and widget tests check different things
A container test checks the logic: given these inputs, the provider holds this state. A widget test checks the wiring: the widget reads the right provider and shows the right thing for each state.
You do not need two sets of fakes for these. A ProviderScope takes the same overrides list as a ProviderContainer. Internally, a ProviderScope creates its own container from that list. So any override you wrote for a container test also works in a widget test.
| Question | `ProviderContainer` test | Widget test with `ProviderScope` |
|---|---|---|
| What does it check? | State and logic | What the user sees and can tap |
| How do you create it? | `ProviderContainer(overrides: ...)` | `ProviderScope(overrides: ..., child: ...)` |
| Who disposes it? | You, with `addTearDown` | The widget tree, when the test ends |
| How do you read state? | `container.read` | `find` and `expect`, or `ProviderScope.containerOf` |
| How fast is it? | Fastest | Slower, because it builds widgets |
The code under test
The examples use the repository and providers from the earlier chapters, plus two small widgets. Put this support code at the top of a test file. The test blocks that follow each define their own main, so keep only one of them in the file at a time.
import 'dart:async';
import 'package:flutter/material.dart';
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 userNameProvider = FutureProvider<String>(
(ref) => ref.watch(userRepositoryProvider).fetchName(),
);
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
class UserNameView extends ConsumerWidget {
const UserNameView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final name = ref.watch(userNameProvider);
return name.when(
loading: () => const Text('Loading'),
error: (error, _) => const Text('Failed to load'),
data: (value) => Text('Hello, $value'),
);
}
}
class CounterView extends ConsumerWidget {
const CounterView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final count = ref.watch(counterProvider);
return Column(
children: [
Text('Count: $count'),
ElevatedButton(
onPressed: () => ref.read(counterProvider.notifier).increment(),
child: const Text('Add'),
),
],
);
}
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName() async => throw Exception('offline');
}
/// Builds a fresh list of overrides, so no fake is shared between tests.
List<Override> fakeOverrides({UserRepository? repository}) => [
userRepositoryProvider
.overrideWithValue(repository ?? FakeUserRepository()),
];
Future<void> pumpApp(
WidgetTester tester,
Widget child, {
List<Override> overrides = const [],
}) {
return tester.pumpWidget(
ProviderScope(
overrides: overrides,
child: MaterialApp(home: Scaffold(body: child)),
),
);
}Two helpers here matter for reuse.
fakeOverridesis a function, not a top-levelfinallist. Each call creates a newFakeUserRepository. If a fake keeps state, such as a call counter, a shared instance would carry that state from one test into the next.pumpAppwraps any widget in aProviderScopeand aMaterialApp.Textneeds the directionality and theme thatMaterialAppprovides. Every widget test then needs only one line of setup.
Testing a widget that reads an async provider
The FakeUserRepository from the container test works here without changes.
void main() {
testWidgets('shows the name returned by the repository', (tester) async {
await pumpApp(tester, const UserNameView(), overrides: fakeOverrides());
// The first frame is built before the Future completes.
expect(find.text('Loading'), findsOneWidget);
// Let the Future complete, then rebuild.
await tester.pump();
expect(find.text('Hello, Ada'), findsOneWidget);
});
testWidgets('shows an error message when the repository fails',
(tester) async {
await pumpApp(
tester,
const UserNameView(),
overrides: fakeOverrides(repository: FailingUserRepository()),
);
await tester.pump();
expect(find.text('Failed to load'), findsOneWidget);
});
}pumpWidget builds the first frame. At that point the FutureProvider has started its work but has no result, so the widget shows the loading branch. tester.pump() lets pending microtasks run and then rebuilds, so the widget sees the data or the error. The second test covers the same error path as the container test, now through the UI.
Controlling timing with a Completer
An async fake finishes almost at once, so you cannot hold the loading state open or decide when the result arrives. A fake that waits on a Completer gives you that control.
class ControlledUserRepository implements UserRepository {
final completer = Completer<String>();
@override
Future<String> fetchName() => completer.future;
}
void main() {
testWidgets('moves from loading to data when the future completes',
(tester) async {
final repository = ControlledUserRepository();
await pumpApp(
tester,
const UserNameView(),
overrides: fakeOverrides(repository: repository),
);
expect(find.text('Loading'), findsOneWidget);
repository.completer.complete('Grace');
await tester.pump();
expect(find.text('Hello, Grace'), findsOneWidget);
expect(find.text('Loading'), findsNothing);
});
}This makes the order of events explicit. Each state appears when you complete the Completer, not when a timer fires.
Overriding a notifier
Fake repositories replace what a provider depends on. Sometimes you want to replace the notifier itself, so the widget starts from a chosen state. Subclass the real notifier and override build. Then pass it to overrideWith, which takes a function that creates the notifier.
class PresetCounter extends Counter {
PresetCounter(this.start);
final int start;
@override
int build() => start;
}
void main() {
testWidgets('starts from the preset value and increments on tap',
(tester) async {
await pumpApp(
tester,
const CounterView(),
overrides: [
counterProvider.overrideWith(() => PresetCounter(5)),
],
);
expect(find.text('Count: 5'), findsOneWidget);
await tester.tap(find.text('Add'));
await tester.pump();
expect(find.text('Count: 6'), findsOneWidget);
});
}PresetCounter inherits increment from Counter. The widget therefore runs the real mutation logic, and only the starting state is controlled. This avoids tapping the button five times to reach a state you want to test.
Reading state from inside a widget test
Sometimes the screen alone does not show what you want to check. For example, the state may change with no visible text. You can get the container behind the ProviderScope and read it as you would in a container test.
void main() {
testWidgets('tapping the button updates the provider state', (tester) async {
await pumpApp(tester, const CounterView());
final container = ProviderScope.containerOf(
tester.element(find.byType(CounterView)),
);
expect(container.read(counterProvider), 0);
await tester.tap(find.text('Add'));
await tester.pump();
expect(container.read(counterProvider), 1);
expect(find.text('Count: 1'), findsOneWidget);
});
}tester.element(...) returns a BuildContext below the scope, and ProviderScope.containerOf finds the nearest container above it. You can then check the provider and the UI in the same test.
Passing in a container you created
Instead of asking the scope for its container, you can create the container first and hand it to the widget tree with UncontrolledProviderScope. This lets you reuse the createContainer helper from the earlier chapter, and any listeners you set up with container.listen.
ProviderContainer createContainer({List<Override> overrides = const []}) {
final container = ProviderContainer(overrides: overrides);
addTearDown(container.dispose);
return container;
}
void main() {
testWidgets('a container made outside the tree drives the widget',
(tester) async {
final container = createContainer(overrides: fakeOverrides());
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: const MaterialApp(home: Scaffold(body: UserNameView())),
),
);
await tester.pump();
expect(find.text('Hello, Ada'), findsOneWidget);
expect(container.read(userNameProvider).value, 'Ada');
});
}Choosing between the approaches
- Use
ProviderScopewithoverridesby default. It matches how the real app is built and needs the least code. - Use
ProviderScope.containerOfwhen you need a single check on provider state, and the rest of the test works through the UI. - Use
UncontrolledProviderScopewhen the test needs to set up or observe the container before or while the widget runs. An example is recording a sequence of states withcontainer.listen.
Pitfalls
- Forgetting to pump. After a tap or a Future completing, the widget still shows the old state until you call
tester.pump(). A test that checks too early fails even though the code is correct. - Forgetting an override. The
userRepositoryProviderabove throwsUnimplementedErroron purpose. If a test forgets to override it, the error flows into theFutureProviderand can appear as the error state. The test then fails with "Failed to load" in an unexpected place. When a widget test shows an error you did not plan, check the override list first. - Sharing one fake between tests. A top-level list holding a single fake keeps its state across tests, which makes results depend on test order. Build the list in a function, as
fakeOverridesdoes. - Using
pumpAndSettlewithout thinking. It keeps pumping until no frames are scheduled. With an endless animation or a repeating timer it never settles and the test times out. Prefer a plainpump()when you know exactly one rebuild is needed. - Overriding too much. If you replace every provider, the test checks only your fakes. Override the edges, such as repositories and clients, and let the real notifiers and derived providers run.
Exercise
A widget test for UserNameView calls pumpWidget and then immediately expects find.text('Hello, Ada') to find one widget, using FakeUserRepository. The test fails and shows 'Loading' instead. What is missing, and why does the fake's use of async not prevent this?
Show answer
The test needs await tester.pump() after pumpWidget. The first frame is built before the FutureProvider's Future completes, even for a fake that returns right away with async. The result becomes available only after the pending microtasks run, and pump() runs them and rebuilds the widget, so the data branch replaces the loading branch.
Exercise
You write final testOverrides = [userRepositoryProvider.overrideWithValue(CountingRepository())]; at the top level of a test file, where CountingRepository records how many times fetchName was called. Two widget tests then assert on the call count, and the second one fails only when the whole file runs. Why, and how do you fix it?
Show answer
Both tests receive the same CountingRepository instance, so the count from the first test is still there when the second runs, and the result depends on test order. Fix it by building the list in a function, such as List<Override> testOverrides() => [userRepositoryProvider.overrideWithValue(CountingRepository())];, and call it inside each test so each test gets a fresh fake.
Exercise
Why does a test that uses UncontrolledProviderScope need addTearDown(container.dispose), while a test that uses ProviderScope does not?
Show answer
ProviderScope creates its own container and disposes it when it is removed from the widget tree, which happens when the test ends. UncontrolledProviderScope only uses a container you supply and does not own it, so it never disposes it. The test must dispose the container itself, and registering addTearDown(container.dispose) does that.