Sub topic 11
Reusing Overrides in Widget Tests
This chapter assumes you know basic Dart tests, Flutter widget tests, and Riverpod providers. It focuses on connecting plain ProviderContainer tests to widget tests.
A ProviderContainer is useful when you want to test provider logic without building a widget tree. A widget test needs a ProviderScope instead. ProviderScope creates and owns the container used by the widgets below it.
The important connection is that both APIs accept provider overrides. You can use the same fake repository and the same override in both kinds of tests.
Passing an override through `ProviderScope`
Suppose a widget displays a username from a repository:
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 UserNameText extends ConsumerWidget {
const UserNameText({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final userName = ref.watch(userNameProvider);
return userName.when(
data: (name) => Text(name),
loading: () => const CircularProgressIndicator(),
error: (error, stackTrace) => const Text('Could not load user'),
);
}
}
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
void main() {
testWidgets('displays the name from the overridden repository', (
tester,
) async {
await tester.pumpWidget(
ProviderScope(
overrides: [
userRepositoryProvider.overrideWithValue(
FakeUserRepository(),
),
],
child: const MaterialApp(
home: Scaffold(
body: UserNameText(),
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Ada'), findsOneWidget);
});
}The ProviderScope override changes the dependency for every provider and widget beneath that scope. userNameProvider still runs its normal code, but its ref.watch(userRepositoryProvider) expression now receives the fake repository.
pumpWidget builds the widget tree. The first build may show the loading state. pumpAndSettle runs pending asynchronous work and rebuilds until there are no more scheduled frames. The final assertion checks the rendered result.
Sharing setup between container and widget tests
A useful pattern is to create the override list once and pass it to either test harness:
final testUserOverrides = <Override>[
userRepositoryProvider.overrideWithValue(
FakeUserRepository(),
),
];A plain provider test can use the list like this:
final container = ProviderContainer(
overrides: testUserOverrides,
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');A widget test can use the same list like this:
await tester.pumpWidget(
ProviderScope(
overrides: testUserOverrides,
child: const MaterialApp(
home: Scaffold(body: UserNameText()),
),
),
);This keeps dependency configuration consistent. If the production provider changes, both tests continue to describe the same dependency boundary.
Testing different widget outcomes
Overrides are also useful for error cases. Replace the successful fake with one that throws:
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName() async => throw Exception('offline');
}Then override the repository with FailingUserRepository() and call pumpAndSettle. The widget should display Could not load user. This tests the complete path from a dependency failure to an AsyncValue.error state and finally to visible UI.
A widget test should assert the behavior a user can observe. A container test should usually assert provider values, notifier state, or thrown errors directly.
How the two test harnesses relate
Common mistakes
- Putting the override on a provider that the widget does not actually watch.
- Forgetting
ProviderScope, which causes the widget to use the production dependency. - Calling
pumponce and asserting before the future completes. - Using
pumpAndSettlewith a widget that intentionally animates forever. - Reusing a mutable fake across tests without resetting its state.
- Adding overrides to a parent scope and accidentally changing unrelated widgets.
When a widget is already inside an application-level ProviderScope, you can add a test scope below it. The nearest scope's override takes effect for the subtree below that scope.
Exercise
A widget test still displays the production repository result after you create a fake. What should you check first?
Show answer
Check that the widget is below the ProviderScope containing the override, and that the override targets the exact provider the widget watches.