Sub topic 13
Unit Testing a View Model with a Fake Repository
Prerequisites
Assume you know basic Dart classes, async and await, Flutter’s ChangeNotifier, and the TodoListViewModel and TodoRepository types from earlier chapters. A unit test checks one class without building widgets. This makes view model tests fast and focused.
The view model should depend on the repository interface, not on a concrete API client. A fake repository is a small test implementation of that interface. It lets each test control returned data and failures.
Create a fake repository
The fake stores todos in memory. Its shouldFail flag lets a test simulate a failed request.
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
class Todo {
const Todo({
required this.id,
required this.title,
this.done = false,
});
final int id;
final String title;
final bool done;
Todo copyWith({bool? done}) {
return Todo(
id: id,
title: title,
done: done ?? this.done,
);
}
}
abstract class TodoRepository {
Future<List<Todo>> fetchTodos();
Future<void> setDone(int id, bool done);
}
class TodoListViewModel extends ChangeNotifier {
TodoListViewModel({required TodoRepository repository})
: _repository = repository;
final TodoRepository _repository;
List<Todo> _todos = const [];
bool _isLoading = false;
Object? _error;
List<Todo> get todos => _todos;
bool get isLoading => _isLoading;
Object? get error => _error;
Future<void> load() async {
_isLoading = true;
_error = null;
notifyListeners();
try {
_todos = await _repository.fetchTodos();
} catch (exception) {
_error = exception;
} finally {
_isLoading = false;
notifyListeners();
}
}
Future<void> toggle(Todo todo) async {
try {
await _repository.setDone(todo.id, !todo.done);
_todos = await _repository.fetchTodos();
_error = null;
} catch (exception) {
_error = exception;
}
notifyListeners();
}
}
class FakeTodoRepository implements TodoRepository {
FakeTodoRepository(this.todos, {this.shouldFail = false});
List<Todo> todos;
final bool shouldFail;
@override
Future<List<Todo>> fetchTodos() async {
if (shouldFail) {
throw Exception('repository failed');
}
return List<Todo>.of(todos);
}
@override
Future<void> setDone(int id, bool done) async {
todos = [
for (final todo in todos)
todo.id == id ? todo.copyWith(done: done) : todo,
];
}
}
void main() {
test('load exposes todos and clears loading state', () async {
final viewModel = TodoListViewModel(
repository: FakeTodoRepository([
const Todo(id: 1, title: 'Write a test'),
]),
);
await viewModel.load();
expect(viewModel.todos, hasLength(1));
expect(viewModel.todos.single.title, 'Write a test');
expect(viewModel.isLoading, isFalse);
expect(viewModel.error, isNull);
viewModel.dispose();
});
test('load records a repository error', () async {
final viewModel = TodoListViewModel(
repository: FakeTodoRepository(
const [],
shouldFail: true,
),
);
await viewModel.load();
expect(viewModel.todos, isEmpty);
expect(viewModel.isLoading, isFalse);
expect(viewModel.error, isNotNull);
viewModel.dispose();
});
test('toggle changes the selected todo', () async {
final viewModel = TodoListViewModel(
repository: FakeTodoRepository([
const Todo(id: 1, title: 'Finish chapter'),
]),
);
await viewModel.load();
await viewModel.toggle(viewModel.todos.single);
expect(viewModel.todos.single.done, isTrue);
viewModel.dispose();
});
}Run this file with flutter test. Each test creates its own fake, so state from one test cannot affect another. The await before load and toggle is important. Without it, assertions could run before asynchronous work finishes.
What these tests verify
| Test | Behavior checked |
|---|---|
| Successful load | Todos are exposed and loading ends |
| Failed load | The error is stored and loading ends |
| Toggle | The repository update appears in view model state |
Tests should check observable behavior, such as todos, isLoading, and error. They should not check private fields or the internal order of method calls. This keeps tests useful when the implementation changes.
Test the state transition
A listener test can verify that the view model notifies the view. Usually, state assertions are enough, because a ListenableBuilder reacts to those notifications. Add a listener test when notification timing is part of the contract, such as showing a progress indicator immediately.
Exercise
Why should a view model test use a fake repository instead of making a real network request?
Show answer
A fake makes the test fast, repeatable, and able to verify both success and failure without depending on network availability.