Sub topic 4
Testing a Notifier's methods and state
A Notifier holds state and the methods that change it. The logic worth testing sits in those methods: which transitions are allowed, what the initial state is, and how the notifier uses its dependencies. This chapter shows how to test that logic with a ProviderContainer and no widgets.
It assumes you can write tests with flutter_test (test, group, expect, addTearDown). It also assumes you know the basics of NotifierProvider, and that you understand the difference between ref.watch and ref.read.
What you are testing
A notifier test follows one pattern: set up, act, assert.
- Create a container and register its disposal.
- Read the provider to get the initial state, which runs
build(). - Read
provider.notifierand call a method. - Read the provider again and assert on the new state.
You never construct the notifier yourself with Counter(). A notifier gets its ref only when the container creates it. Calling Counter().increment() directly fails because the notifier has no ref and no state yet. Always go through the container.
A first notifier test
Here is a counter with a guard. decrement must never go below zero. That rule is the behavior you want a test to protect.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class Counter extends Notifier<int> {
@override
int build() => 0;
void increment() => state++;
void decrement() {
if (state == 0) return;
state--;
}
void reset() => state = 0;
}
final counterProvider = NotifierProvider<Counter, int>(Counter.new);
void main() {
group('Counter', () {
test('starts at zero', () {
final container = ProviderContainer();
addTearDown(container.dispose);
expect(container.read(counterProvider), 0);
});
test('increment adds one', () {
final container = ProviderContainer();
addTearDown(container.dispose);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
});
test('decrement does not go below zero', () {
final container = ProviderContainer();
addTearDown(container.dispose);
container.read(counterProvider.notifier).decrement();
expect(container.read(counterProvider), 0);
});
test('reset returns to zero', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final notifier = container.read(counterProvider.notifier);
notifier.increment();
notifier.increment();
notifier.reset();
expect(container.read(counterProvider), 0);
});
});
}Each test builds its own container, so no test can see another test's state. Registering container.dispose with addTearDown runs the cleanup even when an assertion fails.
Two reads, two different things
container.read(counterProvider) returns the current state, which is an int here. container.read(counterProvider.notifier) returns the notifier object, whose methods you call. Both reads hit the same instance inside one container.
Because the notifier instance is stable, you can keep a reference and call several methods on it, as the reset test does. The state is not stored on the notifier reference. Read the provider again after each action instead of caching the value:
test('reading state before and after a change', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final before = container.read(counterProvider);
container.read(counterProvider.notifier).increment();
final after = container.read(counterProvider);
expect(before, 0);
expect(after, 1);
});The before variable is a snapshot of an int, so it stays 0. It does not follow later changes.
Testing state that holds a collection
Notifiers that hold lists or maps should replace the state with a new object rather than mutate the old one. Riverpod notifies listeners when the new state is not equal to the old state, as decided by identical or == depending on the provider. If you mutate a list in place and reassign the same instance, listeners may not be told.
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
class CartNotifier extends Notifier<List<String>> {
@override
List<String> build() => const [];
void add(String item) {
state = [...state, item];
}
void remove(String item) {
state = state.where((e) => e != item).toList();
}
void clear() => state = const [];
}
final cartProvider = NotifierProvider<CartNotifier, List<String>>(
CartNotifier.new,
);
void main() {
test('add appends items in order', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final cart = container.read(cartProvider.notifier);
cart.add('apple');
cart.add('pear');
expect(container.read(cartProvider), ['apple', 'pear']);
});
test('add replaces the list instead of mutating it', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final before = container.read(cartProvider);
container.read(cartProvider.notifier).add('apple');
final after = container.read(cartProvider);
expect(before, isEmpty);
expect(after, ['apple']);
expect(identical(before, after), isFalse);
});
test('remove drops only the matching item', () {
final container = ProviderContainer();
addTearDown(container.dispose);
final cart = container.read(cartProvider.notifier);
cart.add('apple');
cart.add('pear');
cart.remove('apple');
expect(container.read(cartProvider), ['pear']);
});
}The second test checks the immutability contract directly. If a future change turns add into an in-place state.add(item), before would no longer be empty and the test would fail. That catches a bug that causes missed UI rebuilds.
Notifiers with dependencies
Real notifiers rarely stand alone. They read configuration, repositories, or other providers through ref. A test controls those inputs with overrides, which later chapters cover in full. Here is the simplest case, a limit supplied by another provider:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final maxCountProvider = Provider<int>((ref) => 10);
class LimitedCounter extends Notifier<int> {
@override
int build() => 0;
void increment() {
final max = ref.read(maxCountProvider);
if (state >= max) return;
state++;
}
}
final limitedCounterProvider = NotifierProvider<LimitedCounter, int>(
LimitedCounter.new,
);
void main() {
test('increment stops at the configured maximum', () {
final container = ProviderContainer(
overrides: [maxCountProvider.overrideWithValue(2)],
);
addTearDown(container.dispose);
final counter = container.read(limitedCounterProvider.notifier);
counter.increment();
counter.increment();
counter.increment();
expect(container.read(limitedCounterProvider), 2);
});
}The production default is 10, which would need ten calls to reach the limit. The override sets it to 2, so the test is short and the boundary is obvious. Override inputs to make edge cases cheap to reach.
Testing the initial state when build depends on something
build() can compute the starting state from other providers. In that case the initial state is part of the behavior you should test:
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
final startValueProvider = Provider<int>((ref) => 0);
class StartingCounter extends Notifier<int> {
@override
int build() => ref.watch(startValueProvider);
void increment() => state++;
}
final startingCounterProvider = NotifierProvider<StartingCounter, int>(
StartingCounter.new,
);
void main() {
test('build uses the start value', () {
final container = ProviderContainer(
overrides: [startValueProvider.overrideWithValue(5)],
);
addTearDown(container.dispose);
expect(container.read(startingCounterProvider), 5);
container.read(startingCounterProvider.notifier).increment();
expect(container.read(startingCounterProvider), 6);
});
}Because build uses ref.watch, the notifier rebuilds and resets its state whenever startValueProvider changes. A method-level state++ is lost when that happens. Notifiers that watch inside build therefore have a second behavior to test: what happens to state when the dependency changes.
Resetting a notifier with invalidate
You sometimes need to test that a notifier returns to its initial state after being reset. container.invalidate discards the current state, and the next read runs build() again:
test('invalidate rebuilds the notifier from build()', () {
final container = ProviderContainer();
addTearDown(container.dispose);
container.read(counterProvider.notifier).increment();
expect(container.read(counterProvider), 1);
container.invalidate(counterProvider);
expect(container.read(counterProvider), 0);
});This test reuses the Counter and counterProvider from the first example. It also confirms that all state lives in the container, not in static or global fields.
What to assert
| You want to check | How |
|---|---|
| Initial state | Read the provider before calling any method. |
| A method's effect | Call it through `provider.notifier`, then read the provider. |
| A rule or guard | Call the method in the blocked situation and assert the state is unchanged. |
| Dependency-driven behavior | Override the dependency, then act and assert. |
| Immutability of collections | Keep the old value and compare it with the new one. |
| Reset behavior | Call `container.invalidate(provider)` and read again. |
| Sequence of changes | Use `container.listen`, covered in a later chapter. |
Common mistakes
- Constructing the notifier directly.
Counter()has noref, so methods that touchstateorreffail. Read it from the container. - Sharing a container between tests. State from one test leaks into the next, and results depend on test order. Create a container inside each test, or in
setUp. - Caching
statein a variable and expecting it to update. Re-read the provider after each action. - Asserting only the happy path. A guard like the
decrementcheck needs its own test that triggers the guard. - Forgetting disposal. Without
addTearDown(container.dispose), providers keep their resources until the process ends.
Summary
A notifier test creates a container per test, registers container.dispose with addTearDown, and reads provider for state and provider.notifier for methods. It changes state only through the notifier's public methods. Override the providers the notifier depends on to reach edge cases quickly. Check that collections are replaced rather than mutated. Use container.invalidate to test reset behavior.
Exercise
A TodoNotifier extends Notifier<List<String>> has a method add(String title) that ignores empty titles. Describe the two tests you would write for add, and say which provider reads each one needs.
Show answer
First test: call container.read(todoProvider.notifier).add('Buy milk'), then read todoProvider and expect ['Buy milk']. Second test: call add(''), then read todoProvider and expect it to be empty, which proves the guard works. Each test needs a read of todoProvider.notifier to call the method and a read of todoProvider to get the state. Each test creates its own ProviderContainer and registers container.dispose with addTearDown.
Exercise
Why does a test that keeps final before = container.read(cartProvider); and later compares it to a new read prove that add does not mutate the list in place?
Show answer
The before variable holds a reference to the old list object. If add mutated that list, before would contain the new item and identical(before, after) would be true. Because add assigns a new list to state, before stays empty and identical(before, after) is false.