Sub topic 3
Testing FutureProviders and Error States
This chapter assumes you know Riverpod's Provider, FutureProvider, and NotifierProvider, the difference between ref.watch and ref.read, and how to write tests with package:flutter_test. You should also be comfortable with async/await.
Testing FutureProviders
A FutureProvider exposes an AsyncValue. Reading provider.future returns the underlying Future, which a test can await. Replace the repository with a fake so the test does not touch a real data source.
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 FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName() async => throw Exception('offline');
}
void main() {
test('returns the name', () async {
final container = ProviderContainer(overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
]);
addTearDown(container.dispose);
expect(await container.read(userNameProvider.future), 'Ada');
});
test('surfaces repository errors', () async {
final container = ProviderContainer(overrides: [
userRepositoryProvider.overrideWithValue(FailingUserRepository()),
]);
addTearDown(container.dispose);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
});
}Recording State Changes with container.listen
container.listen calls a callback on every change. Collect the values in a list to assert on the full sequence of states, not only the last one.
Keeping Auto-Dispose Providers Alive
An auto-dispose provider resets when no one listens to it. Hold a subscription open for the length of the test:
final sub = container.listen(autoCounterProvider, (_, __) {});
// ... run assertions ...
sub.close();Extracting a createContainer Helper
Repeated setup is easier to maintain in one helper that registers disposal:
ProviderContainer createContainer({List<Override> overrides = const []}) {
final container = ProviderContainer(overrides: overrides);
addTearDown(container.dispose);
return container;
}Reusing Overrides in Widget Tests
The same overrides list works in widget tests. Pass it to ProviderScope(overrides: ...) in pumpWidget, so the widget and the container tests share one set of fakes.
Pitfalls
- Shared containers: A container reused across tests carries state from one test to the next. Create one per test.
- Unawaited futures: Reading
.futurewithoutawaitlets the assertion run before the value arrives, so the test can pass falsely. Await it or useexpectLater. - Leaked state: Forgetting
addTearDown(container.dispose)leaves providers alive and can affect later tests.
Exercise
A test reads userNameProvider.future without await and then checks the result. Why can this give a false pass?
Show answer
The assertion can run before the future completes, so the test may check an unfinished value or never see the error. Await the future or use expectLater so the test waits for the outcome.