Sub topic 12
Pitfalls: Shared Containers, Unawaited Futures, and Leaked State
Assume you know Dart testing with package:test or flutter_test, including test, expect, and addTearDown. You should also know basic Riverpod providers, ProviderContainer, NotifierProvider, FutureProvider, and Dart Future values.
Provider tests are isolated only when their container, asynchronous work, and subscriptions are isolated. Most confusing failures come from breaking one of those boundaries. A test may pass alone but fail in a suite because it receives state, overrides, or pending work from another test.
Sharing a ProviderContainer between tests
A ProviderContainer stores provider state. It also stores overrides, caches dependencies, and manages provider lifecycles. Reusing one container across tests allows the first test to change what the second test observes.
This pattern is unsafe:
final container = ProviderContainer();
test('first test', () {
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
test('second test', () {
expect(container.read(counterProvider), 0);
});The second test sees 1, because the container still contains the first test's state. Test order can then change the result.
Create and dispose a container inside every test instead:
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);
void main() {
test('starts at zero', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(counterProvider), 0);
});
test('increment changes only this test container', () {
final container = ProviderContainer();
addTearDown(container.dispose);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
}addTearDown runs whether the test succeeds or fails. This makes disposal reliable and prevents resources from remaining active after a failure.
Forgetting to await asynchronous work
A test that starts a Future without awaiting it can finish before the provider has completed. Assertions may run too early, and errors can appear later as unrelated test failures.
For a FutureProvider, read its .future and await the result:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final delayedValueProvider = FutureProvider<String>((ref) async {
await Future<void>.delayed(const Duration(milliseconds: 10));
return 'ready';
});
void main() {
test('waits for the provider result', () async {
final container = ProviderContainer();
addTearDown(container.dispose);
final value = await container.read(delayedValueProvider.future);
expect(value, 'ready');
});
}Reading container.read(delayedValueProvider) returns an AsyncValue<String>, which is useful when you need to inspect loading, data, or error states. It does not, by itself, make the test wait for completion.
| Test action | Typical result |
|---|---|
| `await container.read(provider.future)` | Waits for success or throws on failure |
| `container.read(provider)` | Immediately returns an `AsyncValue` snapshot |
| Starting a future without `await` | May leave work and errors after the test ends |
Leaking listeners and auto-dispose state
A listener keeps a provider active. If you call container.listen, close the returned subscription when the test no longer needs it. Otherwise, the provider may not dispose, and later assertions can observe unexpected activity.
Auto-dispose providers have the opposite issue. They can reset when no listener remains. If your test expects state to survive between actions, keep a subscription open for that interval:
final subscription = container.listen(
autoCounterProvider,
(previous, next) {},
);
addTearDown(subscription.close);Do not use a listener merely to hide a lifecycle problem. First decide whether resetting after the last listener disappears is the intended behavior.
Overrides and leaked dependencies
Overrides belong to a container. A fake repository in one test should not affect another test because both tests share a container or a mutable fake.
Keep fake data local to the test, and install the override when constructing the container. If a fake records calls, clear or recreate it for each test. In widget tests, apply the same override through ProviderScope:
ProviderScope(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
child: const MyApp(),
)This gives the widget and its providers the same controlled dependency without changing production code.
Exercise
Why can a test that reads a FutureProvider pass when run alone but fail in the full suite?
Show answer
It may leave asynchronous work unawaited, allowing a later test to encounter its result or error. Await the provider's future and dispose the test container.