Sub topic 7
Testing FutureProviders and Error States
This chapter assumes you know Dart futures, async and await, package:test or flutter_test, and basic Riverpod providers. It also assumes you can create and dispose a ProviderContainer, as shown in the previous chapter.
A FutureProvider<T> exposes asynchronous work as an AsyncValue<T>. An AsyncValue represents one of three states:
| State | Meaning | Useful test |
|---|---|---|
| `AsyncLoading` | The future has not finished | Check initial loading behavior |
| `AsyncData<T>` | The future completed successfully | Check the returned value |
| `AsyncError` | The future completed with an error | Check error handling |
For most provider tests, read the provider's .future. This returns a Future<T> that completes with the provider's data or throws the provider's error.
The test flow for an async provider
A test usually follows this sequence:
- Create a fresh
ProviderContainer. - Override external dependencies with a fake.
- Read the provider's
.future. - Await the result.
- Assert on the value or error.
- Dispose the container with
addTearDown.
Testing a successful FutureProvider
Suppose the provider gets a user name from a repository. The repository is a dependency, so the test should replace it. This keeps the test independent from a network, database, or generated test data.
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';
}
void main() {
test('returns the name from the repository', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
addTearDown(container.dispose);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}container.read(userNameProvider.future) starts or observes the provider and gives the test a future to await. The assertion runs only after the repository operation completes.
The provider itself still has an AsyncValue state. If you need to inspect that state, read userNameProvider after the future completes:
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
final state = container.read(userNameProvider);
expect(state, isA<AsyncData<String>>());The .future assertion is usually clearer when the behavior under test is the returned data.
Testing an error
Use a fake that throws the same kind of failure the real dependency can produce. Then assert that the provider's future throws.
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName() async {
throw Exception('offline');
}
}
void main() {
test('surfaces repository errors', () async {
final container = ProviderContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
FailingUserRepository(),
),
],
);
addTearDown(container.dispose);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
});
}After the future fails, the provider contains an AsyncError. You can inspect it when the test needs to verify the error state itself:
try {
await container.read(userNameProvider.future);
fail('Expected the provider to fail');
} catch (_) {
final state = container.read(userNameProvider);
expect(state, isA<AsyncError>());
}Prefer checking a domain-specific error type or message when that detail is part of the contract. Avoid asserting an exact message when the message is only an implementation detail.
Common async test errors
- Forgetting
asyncon the test callback means you cannot useawait. - Forgetting
awaitcan let the test finish before the provider completes. - Using a real repository makes the test slow and dependent on external state.
- Reusing a container can preserve cached provider state between tests.
- Checking
AsyncDataimmediately after starting a future can produce a race. Await completion first. - Disposing the container before the future finishes can interrupt provider cleanup and hide the real failure.
A fake controls the result directly. A mock can also verify calls, such as whether fetchName was invoked once. Use a fake when returned behavior is the main concern, and use a mock when interaction details are part of the contract.
Exercise
Why is container.read(userNameProvider.future) usually better than immediately asserting on container.read(userNameProvider)?
Show answer
The .future gives the test a completion point. After awaiting it, the test can assert on the returned data or the thrown error without racing the provider's asynchronous work.