Sub topic 13
Unit testing a view model with a fake repository
A view model is plain Dart that holds state and calls a repository. You can test it without building a single widget. This chapter shows how to write a fake repository, drive the view model, and assert on the state it exposes.
This chapter assumes you have read the earlier chapters on ChangeNotifier, repositories, and dependency injection. You should know async/await and the basics of flutter_test (test, expect, matchers). The examples use the TodoListViewModel and TodoRepository from the previous chapters.
Why a fake, not a mock or the real thing
The view model depends on the TodoRepository interface. Because it receives the repository through its constructor, a test can pass in any class that implements that interface. You have three choices:
| Test double | What it is | Trade-off |
|---|---|---|
| Real repository | The production implementation, possibly calling a network | Slow, flaky, hard to force failures |
| Mock | Generated object that records calls and returns scripted values | Tests often check how the view model calls the repository, which breaks when you refactor |
| Fake | A small hand-written class with a simple working implementation | You write it once, and tests check results instead of calls |
For view models, fakes work well. A view model's job is to turn repository results into UI state, so the useful assertion is "given this data, the state looks like this". A fake lets you set up the data directly.
Setting up the test project
Run these tests with flutter test. ChangeNotifier lives in package:flutter/foundation.dart, which depends on the Flutter engine libraries, so dart test alone will not work.
The examples assume a package named todo_app with this layout:
lib/data/todo_repository.dartcontainsTodo,TodoRepository, andInMemoryTodoRepository.lib/ui/todo_list_view_model.dartcontainsTodoListViewModel.test/fakes/fake_todo_repository.dartholds the fake.test/todo_list_view_model_test.dartholds the tests.
Adjust the import paths if your project differs.
Writing a configurable fake
A fake that only succeeds cannot test error handling. Give it switches that the test can flip, and a way to pause a call so you can look at the state in the middle of loading.
// test/fakes/fake_todo_repository.dart
import 'dart:async';
import 'package:todo_app/data/todo_repository.dart';
class FakeTodoRepository implements TodoRepository {
FakeTodoRepository(
List<Todo> todos, {
this.failOnFetch = false,
this.failOnSetDone = false,
this.gate,
}) : todos = List.of(todos);
List<Todo> todos;
bool failOnFetch;
bool failOnSetDone;
/// When set, fetchTodos waits until the completer is completed.
Completer<void>? gate;
int fetchCalls = 0;
@override
Future<List<Todo>> fetchTodos() async {
fetchCalls++;
await gate?.future;
if (failOnFetch) throw Exception('network down');
return List.of(todos);
}
@override
Future<void> setDone(int id, bool done) async {
if (failOnSetDone) throw Exception('save failed');
todos = [
for (final t in todos) t.id == id ? t.copyWith(done: done) : t,
];
}
}The fake keeps its own list, so a setDone call changes what the next fetchTodos returns. That mirrors how a real repository behaves, and the view model's toggle method (which writes, then refetches) works against it without any scripting.
The gate completer is the key tool for testing intermediate states. Without it, await vm.load() finishes before you can inspect isLoading == true.
Testing the success and failure paths
Start with the cases the view model must get right: the happy path, and the failure path where the repository throws.
// test/todo_list_view_model_test.dart
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:todo_app/data/todo_repository.dart';
import 'package:todo_app/ui/todo_list_view_model.dart';
import 'fakes/fake_todo_repository.dart';
void main() {
late FakeTodoRepository repository;
late TodoListViewModel vm;
setUp(() {
repository = FakeTodoRepository([
const Todo(id: 1, title: 'A'),
const Todo(id: 2, title: 'B', done: true),
]);
vm = TodoListViewModel(repository: repository);
addTearDown(vm.dispose);
});
test('starts empty and idle', () {
expect(vm.todos, isEmpty);
expect(vm.isLoading, isFalse);
expect(vm.error, isNull);
});
test('load exposes todos and clears the loading flag', () async {
await vm.load();
expect(vm.todos.map((t) => t.title), ['A', 'B']);
expect(vm.isLoading, isFalse);
expect(vm.error, isNull);
});
test('load records an error when the repository fails', () async {
repository.failOnFetch = true;
await vm.load();
expect(vm.error, isA<Exception>());
expect(vm.isLoading, isFalse);
expect(vm.todos, isEmpty);
});
}setUp runs before every test, so each test gets a fresh fake and view model. Tests that share state through a repository are a common source of order-dependent failures. addTearDown(vm.dispose) disposes the view model after each test, which matches what a widget tree would do in the app.
Note that the failure test asserts the final state (error set, isLoading false), not that fetchTodos was called. If you later change load to retry once, the test still passes.
Testing the loading state in the middle
To observe isLoading == true, start the call without awaiting it, check the state, then release the gate.
test('isLoading is true while the repository is working', () async {
final gate = Completer<void>();
repository.gate = gate;
final pending = vm.load();
expect(vm.isLoading, isTrue);
gate.complete();
await pending;
expect(vm.isLoading, isFalse);
expect(vm.todos, hasLength(2));
});This works because an async function runs synchronously until its first await. load sets _isLoading = true, calls notifyListeners, and then reaches await _repository.fetchTodos(). The call returns a pending Future with the loading state already set.
Testing notifications
A view model that changes state without calling notifyListeners leaves the screen stale. You can test that contract by attaching a listener and counting calls.
test('load notifies when loading starts and when it ends', () async {
var notifications = 0;
vm.addListener(() => notifications++);
await vm.load();
expect(notifications, 2);
});
test('a failed load still notifies at the end', () async {
repository.failOnFetch = true;
var notifications = 0;
vm.addListener(() => notifications++);
await vm.load();
expect(notifications, 2);
});The number 2 comes from the view model's code: one notifyListeners before the fetch and one in finally. If you add a third notification later, the test fails and tells you. Be deliberate about asserting exact counts. They pin down implementation details, so use them where the notification itself is the behavior you care about, and prefer state assertions elsewhere.
Testing user actions
toggle calls setDone, refetches, and updates state. Test both outcomes.
test('toggle flips the done flag', () async {
await vm.load();
await vm.toggle(vm.todos.first);
expect(vm.todos.first.done, isTrue);
expect(vm.error, isNull);
});
test('toggle failure keeps the old list and records the error', () async {
await vm.load();
repository.failOnSetDone = true;
await vm.toggle(vm.todos.first);
expect(vm.todos.first.done, isFalse);
expect(vm.error, isA<Exception>());
});
test('a later successful load clears an earlier error', () async {
repository.failOnFetch = true;
await vm.load();
expect(vm.error, isNotNull);
repository.failOnFetch = false;
await vm.load();
expect(vm.error, isNull);
expect(vm.todos, hasLength(2));
});The last test checks recovery. Many view models forget to reset _error when a retry starts, and the UI keeps showing the old message.
What to test and what to leave out
- Test the view model's state transitions: initial state, loading, success, failure, recovery.
- Test that actions reach the repository and that the resulting state is correct.
- Do not test that
ListenableBuilderrebuilds. That belongs to the framework, and a widget test covers it if you need one. - Do not test the fake. Keep it small enough that reading it is enough.
- Test
InMemoryTodoRepositoryand any real repository separately. A fake only tells you the view model is correct if the real repository honors the same interface contract.
Common mistakes
- Forgetting
await.vm.load();withoutawaitlets the test body continue before state settles, and assertions pass or fail at random. - Sharing one fake across tests. Build it in
setUp, not at the top ofmain. - Using a real delay. The
InMemoryTodoRepositorywaits 200 ms. A fake should return immediately or wait on aCompleter, which keeps the suite fast and deterministic. - Asserting on error text. Prefer
isA<Exception>()or a custom error type over matching a message string.
Exercise
The view model's toggle method sets _error = null only on success. Write a test, using the fake in this chapter, that proves a failed toggle followed by a successful toggle clears the error. State which fake properties you change between the two calls.
Show answer
Load first, then set repository.failOnSetDone = true and await vm.toggle(vm.todos.first). Assert vm.error is not null. Then set repository.failOnSetDone = false, call await vm.toggle(vm.todos.first) again, and assert vm.error is null. The only property that changes is failOnSetDone. The test passes because toggle assigns _error = null after a successful refetch.
Exercise
Why does the test isLoading is true while the repository is working check vm.isLoading right after vm.load() returns, before any await?
Show answer
An async function runs synchronously until its first await. load sets _isLoading = true and calls notifyListeners before it awaits the fetch, so the flag is already true when the Future is returned. The gate keeps the fetch pending, so the test can observe that state and then release the gate.