Sub topic 2
Testing a Notifier's Methods and State
This chapter assumes you know Dart's async and await, the test and expect functions from flutter_test, and NotifierProvider. You will call a Notifier's methods through a ProviderContainer, check its state, and replace its repository with a fake using overrides.
Testing a Notifier's methods and state
Call a notifier's methods with container.read(provider.notifier). Read its state with container.read(provider). Create the container inside each test and dispose it with addTearDown, so no state carries over between tests.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
abstract class TodoRepository {
Future<void> save(String title);
}
final todoRepositoryProvider = Provider<TodoRepository>(
(ref) => throw UnimplementedError('Override todoRepositoryProvider'),
);
class TodoList extends Notifier<List<String>> {
@override
List<String> build() => [];
Future<void> add(String title) async {
await ref.read(todoRepositoryProvider).save(title);
state = [...state, title];
}
}
final todoListProvider =
NotifierProvider<TodoList, List<String>>(TodoList.new);
class FakeTodoRepository implements TodoRepository {
final saved = <String>[];
@override
Future<void> save(String title) async {
saved.add(title);
}
}
void main() {
test('add appends the title to state', () async {
final fake = FakeTodoRepository();
final container = ProviderContainer(
overrides: [todoRepositoryProvider.overrideWithValue(fake)],
);
addTearDown(container.dispose);
expect(container.read(todoListProvider), isEmpty);
await container.read(todoListProvider.notifier).add('Buy milk');
expect(container.read(todoListProvider), ['Buy milk']);
expect(fake.saved, ['Buy milk']);
});
}Overriding providers to isolate the code under test
The todoRepositoryProvider throws by default, so the test fails if it reaches the real repository. overrideWithValue replaces that provider for one container only. Other tests and the app keep their own wiring.
Writing fakes and mocks for repositories
A fake is a small class that implements the repository interface and records what happened. Your test can then check the fake's recorded data, as the last expect above does. For error handling, write a fake that throws, and assert that the notifier's state does not change.
> Note: the fake must implement the same interface as the real repository. Keep the interface small so fakes stay short.
Exercise
Q: In the example, why does the test still pass if FakeTodoRepository.save is never called?
A: It would fail, because expect(fake.saved, ['Buy milk']) requires the fake to record the call.