Sub topic 10
Extracting a `createContainer` Helper
This chapter assumes you know Dart tests, ProviderContainer, Riverpod providers, and provider overrides. The goal is to remove repeated test setup without sharing state between tests.
Why extract the setup?
A provider test commonly begins with the same code:
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);This setup has two important responsibilities:
- It creates an isolated container for the current test.
- It guarantees that the container is disposed when the test finishes.
Repeating this code in every test makes the test suite noisy. It also makes lifecycle mistakes easier to introduce. A small helper can keep the behavior while making each test focus on its scenario.
Build `createContainer`
The helper accepts an optional list of overrides. An override is a replacement implementation for a provider during a test.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
ProviderContainer createContainer({
List<Override> overrides = const [],
}) {
final container = ProviderContainer(overrides: overrides);
addTearDown(container.dispose);
return container;
}The default value, const [], means most tests can call the helper without arguments. Tests that need fake dependencies pass an override list.
addTearDown registers cleanup for the current test. It runs whether the test succeeds or fails. This is safer than manually calling dispose at the end because an assertion failure could otherwise skip the cleanup code.
The helper must create a new container every time it is called. A container stores provider state, cached values, listeners, and dependency relationships. Sharing one container across tests allows state from one test to affect another test.
Use the helper with ordinary providers
Suppose the application has a notifier that starts at zero:
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);A test can now use the helper directly:
void main() {
test('increment updates state', () {
final container = createContainer();
expect(container.read(counterProvider), 0);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
}container.read(counterProvider) reads the current exposed state. The .notifier property gives access to the notifier instance, so the test can call its public methods.
The helper does not change how providers work. It only centralizes container creation and disposal.
Use overrides when a test needs a fake
The same helper also supports dependency injection:
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 FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
void main() {
test('uses the fake repository', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
FakeUserRepository(),
),
],
);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}The override belongs to this container only. Other tests still receive the normal provider definition or can supply a different fake.
| Test situation | Container setup |
|---|---|
| No replacement dependencies | `createContainer()` |
| Fake or test dependency | `createContainer(overrides: [...])` |
| Widget integration test | `ProviderScope(overrides: [...])` |
Keep the helper focused
A useful helper should handle stable, universal setup. It should not hide test-specific behavior.
Avoid adding application state, listeners, or provider reads to createContainer. Those actions belong in the individual test, where the test's behavior remains visible.
The same override list can be used in a widget test. A widget test uses ProviderScope, which provides a container to the widget tree:
await tester.pumpWidget(
ProviderScope(
overrides: [
userRepositoryProvider.overrideWithValue(
FakeUserRepository(),
),
],
child: const MyApp(),
),
);The direct container test and the widget test can therefore use the same fake dependency while testing different layers.
Exercise
What problem does createContainer solve, and why must it return a new ProviderContainer for each test?
Show answer
It removes repeated setup and disposal code. Each test needs a new container so cached provider state and listeners cannot leak between tests.