Sub topic 11
Testing an AsyncNotifier
This chapter assumes you know Future, async and await, basic Riverpod providers, and Flutter test syntax. The goal is to test an AsyncNotifier without starting a real network client or database.
An AsyncNotifier has two responsibilities that tests should cover:
build()loads the initial value.- Public methods change the value and handle failures.
A ProviderContainer is the test environment for Riverpod providers outside a widget tree. You can override dependencies in that container, such as a repository, with a fake implementation.
Test the initial load
The provider's .future is useful when a test needs to wait for the first successful result. It completes with the data inside AsyncData, or throws if the provider reaches AsyncError.
The following example tests an in-memory repository. The production classes are included so the test can run as one Dart test file.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Todo {
const Todo(this.id, this.title);
final String id;
final String title;
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> addTodo(String title);
}
final todoRepositoryProvider = Provider<TodoRepository>((ref) {
throw UnimplementedError('Override this provider in the application');
});
class TodosNotifier extends AsyncNotifier<List<Todo>> {
@override
Future<List<Todo>> build() {
return ref.watch(todoRepositoryProvider).fetchTodos();
}
Future<void> addTodo(String title) async {
final repository = ref.read(todoRepositoryProvider);
state = const AsyncLoading();
state = await AsyncValue.guard(() async {
await repository.addTodo(title);
return repository.fetchTodos();
});
}
}
final todosProvider =
AsyncNotifierProvider<TodosNotifier, List<Todo>>(TodosNotifier.new);
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('loads the initial todos', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
],
);
addTearDown(container.dispose);
final todos = await container.read(todosProvider.future);
expect(todos, hasLength(1));
expect(todos.single.title, 'Write tests');
});
test('addTodo appends a todo and reloads the list', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider.overrideWithValue(FakeTodoRepository()),
],
);
addTearDown(container.dispose);
await container.read(todosProvider.future);
await container.read(todosProvider.notifier).addTodo('Ship it');
final state = container.read(todosProvider);
expect(state, isA<AsyncData<List<Todo>>>());
expect(state.requireValue, hasLength(2));
expect(state.requireValue.last.title, 'Ship it');
});
}overrideWithValue gives the provider a known dependency. This keeps the test fast and deterministic. addTearDown disposes the container after each test, which prevents provider state from leaking into another test.
requireValue is appropriate after the test has awaited a successful operation. It returns the value from AsyncData, but throws if the state is loading or contains an error. That makes an unexpected state fail the test immediately.
Test error states
A fake can also model a failure. This checks that AsyncValue.guard converts the exception into AsyncError.
class FailingTodoRepository implements TodoRepository {
@override
Future<List<Todo>> fetchTodos() async {
throw StateError('server unavailable');
}
@override
Future<void> addTodo(String title) async {}
}
test('stores an initial load failure as AsyncError', () async {
final container = ProviderContainer(
overrides: [
todoRepositoryProvider
.overrideWithValue(FailingTodoRepository()),
],
);
addTearDown(container.dispose);
await expectLater(
container.read(todosProvider.future),
throwsA(isA<StateError>()),
);
final state = container.read(todosProvider);
expect(state, isA<AsyncError<List<Todo>>>());
expect(state.hasError, isTrue);
});The .future reports the failure to code that is awaiting it. The provider still retains the failure as an AsyncError, so widgets can render an error message.
| What you test | Useful assertion |
|---|---|
| Initial success | `await container.read(provider.future)` |
| Current data | `container.read(provider).requireValue` |
| Failure state | `isA<AsyncError<T>>()` |
| Dependency replacement | `provider.overrideWithValue(fake)` |
Understand the test sequence
A provider may not begin loading until something reads it. Reading .future both starts the provider and waits for its result.
Common testing errors
- Do not use a real repository when a fake can represent the behavior. Real services make tests slow and unreliable.
- Do not assert immediately after calling an asynchronous notifier method. Await the method first.
- Do not reuse one container across unrelated tests. Each test should own and dispose its container.
- Do not inspect only the data path. Test at least one failure path so error handling remains intentional.
Exercise
Why should a test override the repository instead of constructing a real repository?
Show answer
An override isolates the notifier from network, database, timing, and configuration concerns, making the test deterministic and focused on provider behavior.