Sub topic 7
Testing FutureProviders and error states
This chapter assumes you can write tests with flutter_test (test, expect, addTearDown). It also assumes you know how to create a ProviderContainer and override a provider. You should be comfortable with async/await. Here you will test a FutureProvider through its three outcomes: loading, data and error. You will also learn why asynchronous tests that look correct sometimes pass for the wrong reason.
What a FutureProvider exposes
A FutureProvider<T> does not expose a T. It exposes an AsyncValue<T>, a sealed type with three states:
AsyncLoading<T>: the future has not finished.AsyncData<T>: the future completed with a value.AsyncError<T>: the future threw.
The provider also exposes the underlying future through .future. Each form is useful in a test.
| What you read | Type | Use it to |
|---|---|---|
| `container.read(provider)` | `AsyncValue<T>` | Check the current state without waiting |
| `container.read(provider.future)` | `Future<T>` | Wait for completion and get the value or the thrown error |
| `container.listen(provider, ...)` | callback per change | Record the whole sequence of states |
The code under test
The examples in this chapter share one setup. A repository is hidden behind a provider that throws by default, so a test cannot reach a real data source without an explicit override.
import 'dart:async';
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(),
);
ProviderContainer createContainer({List<Override> overrides = const []}) {
final container = ProviderContainer(overrides: overrides);
addTearDown(container.dispose);
return container;
}The createContainer helper creates a fresh container and registers its disposal. Every test below uses it.
Fakes that control the outcome
A fake is a small class that implements the repository interface and returns whatever the test needs. Three fakes cover the three states.
class FakeUserRepository implements UserRepository {
@override
Future<String> fetchName() async => 'Ada';
}
class FailingUserRepository implements UserRepository {
@override
Future<String> fetchName() async => throw Exception('offline');
}
class ControlledUserRepository implements UserRepository {
ControlledUserRepository(this._result);
final Future<String> _result;
@override
Future<String> fetchName() => _result;
}FakeUserRepository produces data. FailingUserRepository produces an error. ControlledUserRepository returns a future that the test owns, which lets the test decide when the result arrives. That control is what makes the loading state testable.
Testing the success path
Override the repository provider, then await .future:
void main() {
test('userNameProvider returns the name from the repository', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
final name = await container.read(userNameProvider.future);
expect(name, 'Ada');
});
}await container.read(userNameProvider.future) does two jobs. It creates the provider, which starts the fetch, and it suspends the test until the future completes. Without the await, the test function would return while the fetch is still running. The test would pass without checking anything.
After the future completes, the provider's AsyncValue has also changed. You can assert on it directly:
void main() {
test('state is AsyncData after the future completes', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
await container.read(userNameProvider.future);
final state = container.read(userNameProvider);
expect(state, isA<AsyncData<String>>());
expect(state.requireValue, 'Ada');
});
}requireValue returns the value and throws a StateError if the state has no value. In a test, that failure is useful because it points at the problem.
Testing the loading state
Right after the first read, the provider is still waiting for its future. To check that state reliably, the fake's future must still be pending at that moment. A Completer gives you that control:
void main() {
test('state is AsyncLoading until the repository completes', () async {
final completer = Completer<String>();
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
ControlledUserRepository(completer.future),
),
],
);
expect(container.read(userNameProvider), isA<AsyncLoading<String>>());
completer.complete('Ada');
await container.read(userNameProvider.future);
expect(container.read(userNameProvider).requireValue, 'Ada');
});
}The first read builds the provider and calls fetchName, which returns the pending future. The state is loading, so the first expect passes. Calling completer.complete('Ada') releases the future. Awaiting .future then waits for the provider to catch up.
Do not try to catch the loading state with FakeUserRepository. Its async function completes on a later microtask, so the loading assertion would currently pass. That would be a coincidence of timing, not something you control. The completer removes the dependence on timing.
Testing the error path
An error thrown inside the future shows up in two places. The .future rejects with the same error, and the AsyncValue becomes an AsyncError.
void main() {
test('userNameProvider surfaces repository errors', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FailingUserRepository()),
],
);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<Exception>()),
);
final state = container.read(userNameProvider);
expect(state, isA<AsyncError<String>>());
expect(state.hasError, isTrue);
expect(state.error.toString(), contains('offline'));
});
}Three details matter here:
- Use
await expectLater(...), not a bareexpect(...). AthrowsAmatcher against a future is asynchronous. Withexpectand noawait, the test can finish before the matcher resolves, and a failure then surfaces after the test is over, or never. - Pass the future itself. Do not write
await container.read(userNameProvider.future)inside the matcher. That would throw beforeexpectLateris called, and the test would fail with the raw exception. - Inspect
state.errorwhen the message matters. Matching onisA<Exception>()alone passes for any exception, including one thrown by an unrelated bug.
For a custom error type, match that type:
class OfflineException implements Exception {
const OfflineException();
}
class OfflineUserRepository implements UserRepository {
@override
Future<String> fetchName() async => throw const OfflineException();
}
void main() {
test('offline errors keep their type', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(OfflineUserRepository()),
],
);
await expectLater(
container.read(userNameProvider.future),
throwsA(isA<OfflineException>()),
);
});
}Recording the sequence of states
Reading the state before and after tells you the endpoints. To check what happened in between, use container.listen with fireImmediately: true. That option calls the listener with the current state when you subscribe.
void main() {
test('state goes from loading to data', () async {
final completer = Completer<String>();
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(
ControlledUserRepository(completer.future),
),
],
);
final states = <AsyncValue<String>>[];
container.listen<AsyncValue<String>>(
userNameProvider,
(previous, next) => states.add(next),
fireImmediately: true,
);
completer.complete('Ada');
await container.read(userNameProvider.future);
expect(states, hasLength(2));
expect(states[0], isA<AsyncLoading<String>>());
expect(states[1], isA<AsyncData<String>>());
expect(states[1].requireValue, 'Ada');
});
}Without fireImmediately, the listener only sees changes. The initial loading state is not a change, so states would contain only the data value. Decide which you want before writing the expected list.
For an error sequence, the second entry is an AsyncError. Listening is also the right tool for providers that move through states more than once, such as after a refresh. See the earlier chapter on container.listen for details.
Auto-dispose providers
A FutureProvider.autoDispose discards its state when nothing is listening. If a test only reads it, the provider may be disposed and rebuilt between steps, and a second fetch may start. Hold a subscription for the whole test:
final autoUserNameProvider = FutureProvider.autoDispose<String>(
(ref) => ref.watch(userRepositoryProvider).fetchName(),
);
void main() {
test('auto-dispose async state survives with a listener', () async {
final container = createContainer(
overrides: [
userRepositoryProvider.overrideWithValue(FakeUserRepository()),
],
);
final subscription = container.listen(autoUserNameProvider, (_, __) {});
await container.read(autoUserNameProvider.future);
expect(subscription.read().requireValue, 'Ada');
subscription.close();
});
}subscription.read() returns the current value of the provider. Reading through the subscription is a good habit here because it makes clear which handle keeps the provider alive.
Common mistakes with async providers
The failures below all produce green tests that prove nothing, or red tests with misleading messages.
- Forgetting
await. A test function that returns before its future completes passes. Any assertion that runs later fails outside the test, or never runs. - Using
expectinstead ofexpectLaterwith an async matcher. See the error path above. - Asserting on
container.read(provider)right after creation and expecting data. The first state is loading, so the assertion fails or, worse, matchesAsyncLoading. - Reusing a container across tests. A cached
AsyncDatafrom an earlier test hides a broken provider. Create one container per test withcreateContainer. - Leaving a failing future unobserved. If a provider's future fails and nothing awaits or listens to it, the error can be reported as unhandled and fail an unrelated test. Always observe the error, as in the error test above.
- Overriding with a value that already completed when you meant to control timing. Use a
Completerwhenever the test depends on ordering.
Summary of the technique
- Hide the data source behind a provider, and override it with a fake.
- Await
container.read(provider.future)for the final value or error. - Read
container.read(provider)to assert onAsyncData,AsyncErrororAsyncLoading. - Use a
Completerwhen the test needs to hold the provider in the loading state. - Use
container.listenwithfireImmediately: trueto record the full sequence. - Hold a listener open for auto-dispose providers.
Exercise
A test overrides the repository with FailingUserRepository and contains this code: expect(container.read(userNameProvider.future), throwsA(isA<Exception>())); The test passes, even when you change the fake so that it no longer throws. What is wrong, and how do you fix it?
Show answer
The expect call is not awaited, and the matcher is asynchronous. The test function returns before the future resolves, so the check is never part of the result. Change it to await expectLater(container.read(userNameProvider.future), throwsA(isA<Exception>()));. With the await, a fake that no longer throws makes the test fail, which is the intended behavior.
Exercise
You want to assert that userNameProvider is in the AsyncLoading state immediately after the first read. Why does FakeUserRepository make that assertion fragile, and what do you use instead?
Show answer
FakeUserRepository.fetchName is an async function that completes on a later microtask, so whether the test sees loading depends on timing it does not control. Use a Completer<String> and a fake such as ControlledUserRepository that returns completer.future. The future stays pending until the test calls completer.complete(...), so the loading assertion holds by construction.
Exercise
What does container.listen record if you leave out fireImmediately: true when testing a loading-to-data transition, and why?
Show answer
It records only the AsyncData state. The listener is called on changes, and the initial AsyncLoading state is the starting value, not a change. With fireImmediately: true, the listener is also called with the current state at subscription time, so the list holds both AsyncLoading and AsyncData.