Sub topic 11
Testing an AsyncNotifier
This chapter covers how to test the TodosNotifier from the earlier chapters without a widget tree, a network or a database. You will work with a ProviderContainer, provider overrides, hand-written fakes, and a widget test that checks the loading state.
Prerequisites and setup
This chapter assumes you have read the earlier chapters and are comfortable with these:
AsyncNotifier,build(), andAsyncValue.guard.AsyncValueand itsisLoading,hasValueandhasErrorflags.- Dart
async/awaitandpackage:flutter_test.
The examples use the Todo, TodoRepository, todoRepositoryProvider and todosProvider definitions from the chapter on declaring the notifier. They assume those live in lib/todos.dart in a package named app. Adjust the import to match your project.
Why a ProviderContainer
A ProviderContainer is the object that stores provider state. In an app, ProviderScope creates one for you. In a test you can create one yourself, so you can test a notifier as plain Dart code.
Tests that use a container have three advantages:
- They run fast, because no widgets are built.
- They give you direct control over the notifier's dependencies.
- They let you read the
AsyncValueat any moment and assert on it.
The key idea is that the notifier never creates its own repository. It reads todoRepositoryProvider, which throws UnimplementedError unless something overrides it. In tests, you provide the override.
A first test: initial load and a mutation
The fake implements the abstract TodoRepository and keeps its data in memory. This test is the one from the spine, with the imports it needs.
import 'package:app/todos.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class FakeTodoRepository implements TodoRepository {
final List<Todo> _todos = [const Todo('1', 'Write tests')];
@override
Future<List<Todo>> fetchTodos() async => List.of(_todos);
@override
Future<void> addTodo(String title) async {
_todos.add(Todo('${_todos.length + 1}', title));
}
}
void main() {
test('addTodo appends and reloads the list', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
],
);
addTearDown(container.dispose);
final initial = await container.read(todosProvider.future);
expect(initial, hasLength(1));
await container.read(todosProvider.notifier).addTodo('Ship it');
expect(container.read(todosProvider).requireValue, hasLength(2));
});
}The test uses several features:
overrideWithValuereplaces the repository provider's value for this container only. Other tests get their own container and their own state.addTearDown(container.dispose)disposes the container when the test ends, even if an assertion fails. Skipping it can leak providers between tests.container.read(todosProvider.future)startsbuild()and waits for it. Without thatawait, the first read returnsAsyncLoadingand your assertions would run too early.container.read(todosProvider.notifier)returns theTodosNotifierinstance, so you can calladdTododirectly. That method returns aFuture, so you can await it.requireValuereturns the data, or throws if the state is loading or an error. In a test, a thrown exception is a clear failure message, which is why it is useful here. In app code, preferwhenor aswitch.
Why `.future` and not `.read` alone
container.read(todosProvider) returns an AsyncValue immediately. Right after creation it is AsyncLoading. The .future getter returns a Future<List<Todo>> that completes when the state becomes data, and fails if it becomes an error. That makes it the natural way to wait for a provider in a test.
Testing failures
The happy path is half the story. The reason to model state as AsyncValue is that errors become values, so you should test them as values.
There are two failure points in the notifier:
build()can fail while loading the list.addTodocan fail while saving.
The notifier handles them differently, and the tests show how. A failure in build() makes the provider's Future complete with an error. A failure in addTodo is caught by AsyncValue.guard, so the method does not throw. The error is stored in state.
import 'package:app/todos.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class FailingTodoRepository implements TodoRepository {
FailingTodoRepository({this.failFetch = false, this.failAdd = false});
final bool failFetch;
final bool failAdd;
@override
Future<List<Todo>> fetchTodos() async {
if (failFetch) throw StateError('offline');
return [const Todo('1', 'Write tests')];
}
@override
Future<void> addTodo(String title) async {
if (failAdd) throw StateError('save failed');
}
}
ProviderContainer makeContainer(TodoRepository repository) {
final container = ProviderContainer(
overrides: [todoRepositoryProvider.overrideWithValue(repository)],
);
addTearDown(container.dispose);
return container;
}
void main() {
test('a failing build() becomes AsyncError', () async {
final container = makeContainer(FailingTodoRepository(failFetch: true));
await expectLater(
container.read(todosProvider.future),
throwsA(isA<StateError>()),
);
final state = container.read(todosProvider);
expect(state.hasError, isTrue);
expect(state.error, isA<StateError>());
});
test('a failing addTodo is stored in state, not thrown', () async {
final container = makeContainer(FailingTodoRepository(failAdd: true));
await container.read(todosProvider.future);
await container.read(todosProvider.notifier).addTodo('Ship it');
final state = container.read(todosProvider);
expect(state.hasError, isTrue);
expect(state.error, isA<StateError>());
});
}The second test does not wrap addTodo in expect(..., throwsA(...)). If it did, the test would fail, because AsyncValue.guard swallows the exception into AsyncError. Writing the test this way documents the contract: callers of addTodo never need try/catch.
The makeContainer helper removes the repeated container setup. Keep one in a shared test file once you have more than a few tests.
Observing state transitions
Sometimes the final state is not enough. You may want to verify that addTodo passes through a loading state, since the UI relies on it to show a spinner. Use container.listen to record every state the provider takes.
import 'package:app/todos.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class InMemoryRepository implements TodoRepository {
final List<Todo> _todos = [const Todo('1', 'Write tests')];
@override
Future<List<Todo>> fetchTodos() async => List.of(_todos);
@override
Future<void> addTodo(String title) async {
_todos.add(Todo('${_todos.length + 1}', title));
}
}
void main() {
test('addTodo goes through loading and ends with data', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(InMemoryRepository()),
],
);
addTearDown(container.dispose);
final states = <AsyncValue<List<Todo>>>[];
container.listen<AsyncValue<List<Todo>>>(
todosProvider,
(previous, next) => states.add(next),
);
await container.read(todosProvider.future);
states.clear();
await container.read(todosProvider.notifier).addTodo('Ship it');
expect(states.first.isLoading, isTrue);
expect(states.last.hasValue, isTrue);
expect(states.last.requireValue, hasLength(2));
});
}The test clears the list after the initial load so that it only inspects the states caused by addTodo. It asserts on the first and last recorded states and does not require an exact number of notifications. The exact count is an implementation detail of Riverpod, and a test that depends on it breaks when the library changes.
The listener also keeps the provider alive. That matters for autoDispose providers. With AsyncNotifierProvider.autoDispose, a bare container.read with no listener can let the provider be disposed between reads. If you test an auto-dispose provider, add container.listen(todosProvider, (_, __) {}) right after creating the container.
Testing the widget layer
Container tests cover the logic. A widget test confirms that the UI maps each AsyncValue case to the right output. Replace the repository with a fake whose Completer you control, so the loading state lasts as long as you need.
import 'dart:async';
import 'package:app/todos.dart';
import 'package:app/todo_list.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class GatedRepository implements TodoRepository {
final Completer<List<Todo>> gate = Completer<List<Todo>>();
@override
Future<List<Todo>> fetchTodos() => gate.future;
@override
Future<void> addTodo(String title) async {}
}
void main() {
testWidgets('TodoList shows a spinner, then the todos', (tester) async {
final repository = GatedRepository();
await tester.pumpWidget(
ProviderScope(
overrides: [todoRepositoryProvider.overrideWithValue(repository)],
child: const MaterialApp(home: Scaffold(body: TodoList())),
),
);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
repository.gate.complete([const Todo('1', 'Write tests')]);
await tester.pump();
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('Write tests'), findsOneWidget);
});
}This test assumes TodoList lives in lib/todo_list.dart. The GatedRepository keeps the notifier in AsyncLoading until the test calls complete. After that, a single tester.pump() lets the widget rebuild with the data.
Avoid pumpAndSettle while the spinner is on screen. CircularProgressIndicator animates forever, so pumpAndSettle would time out.
Choosing the right kind of test
| Question you want answered | Best tool |
|---|---|
| Does `build()` load and map data correctly? | `ProviderContainer` and `.future` |
| Does a failure become `AsyncError`? | `ProviderContainer`, check `hasError` |
| Does a mutation pass through loading? | `container.listen` recording states |
| Does the widget render each case? | `testWidgets` with `ProviderScope` overrides |
| Does a real HTTP or database call work? | Integration test, not a provider test |
Common mistakes
- Forgetting the override. Without it,
todoRepositoryProviderthrowsUnimplementedError, and the test fails insidebuild()with anAsyncError. The message points to the repository provider. - Asserting before the load finishes.
container.read(todosProvider)right after creation isAsyncLoading. Await.futurefirst. - Sharing one container between tests. State leaks from one test to the next. Create a container per test and dispose it with
addTearDown. - Expecting
addTodoto throw. It does not. Checkstate.hasErrorinstead. - Using real delays. A
Future.delayed(Duration(seconds: 1))in a fake slows the suite. ReturnFuturevalues immediately, or use aCompleterfor precise control.
Summary of the testing workflow
- Create a
ProviderContainerwithoverridesthat replace external dependencies with fakes. - Register
container.disposewithaddTearDown. - Await
container.read(provider.future)to runbuild(). - Call methods through
container.read(provider.notifier). - Assert on
container.read(provider)usingrequireValue,hasErroranderror. - Use
container.listenwhen the order of states matters. - Use
testWidgetswithProviderScopeoverrides when you need to check rendering.
Exercise
In the test for a failing addTodo, a teammate writes await expectLater(notifier.addTodo('x'), throwsA(isA<StateError>())) and the test fails even though the repository does throw. Why, and what should the test assert instead?
Show answer
addTodo runs the repository call inside AsyncValue.guard, which catches the exception and stores it in state as an AsyncError. The method's Future therefore completes normally and never throws. The test should await notifier.addTodo('x'), then read container.read(todosProvider) and assert that hasError is true and that error is a StateError.
Exercise
You want to test that the list screen shows a spinner while the first load is running. Which fake would you write, and why is pumpAndSettle a poor choice while the spinner is visible?
Show answer
Write a fake repository whose fetchTodos returns the future of a Completer that the test controls, so the provider stays in AsyncLoading until the test calls complete. pumpAndSettle waits until no frames are scheduled, but CircularProgressIndicator animates continuously, so it never settles and the call times out. Use pump() instead.