Sub topic 14
Testing models with value equality
What you need first
This chapter assumes you can run dart run build_runner build, read a freezed class declaration, and write a basic test or testWidgets case. The tests use package:flutter_test. In a pure Dart package, swap it for package:test and run dart test.
The examples use one model. Save it as lib/person.dart in a package named shop_app, then generate code:
import 'package:freezed_annotation/freezed_annotation.dart';
part 'person.freezed.dart';
part 'person.g.dart';
@freezed
abstract class Person with _$Person {
@Assert('age >= 0')
const factory Person({
required String name,
@Default(0) int age,
@JsonKey(name: 'e_mail') String? email,
}) = _Person;
factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);
}Why value equality simplifies tests
Without value equality, a test that checks a model has to read it field by field. It also has to remember every field, so a new field goes unchecked until someone adds a line. A freezed class generates == and hashCode from all constructor fields. A test can state the whole expected object and let expect compare it.
The generated == has three properties that matter for tests:
- Two instances are equal when they have the same runtime type and every field is equal.
- Fields that are lists, maps or sets are compared by their contents, not by identity.
- Fields of other types are compared with their own
==. A field holding a plain class without==will make two otherwise identical models unequal.
Basic equality tests
Start by testing the guarantees you rely on elsewhere in the app. Equal values should be equal, differing values should not be, and equal values must share a hash code. The hash code matters because Set, Map keys and some Flutter rebuild checks depend on it.
import 'package:flutter_test/flutter_test.dart';
import 'package:shop_app/person.dart';
void main() {
test('instances with equal fields are equal', () {
const a = Person(name: 'Ada', age: 36);
const b = Person(name: 'Ada', age: 36);
expect(a, equals(b));
expect(a.hashCode, b.hashCode);
expect(a.copyWith(age: 37), isNot(equals(a)));
});
test('equal values collapse in a set', () {
final people = {
const Person(name: 'Ada', age: 36),
const Person(name: 'Ada', age: 36),
};
expect(people, hasLength(1));
});
test('omitted fields take their defaults', () {
const p = Person(name: 'Grace');
expect(p, const Person(name: 'Grace', age: 0, email: null));
});
}You do not need to test that freezed works, because the package has its own tests. These tests exist to document behavior your app depends on. They also catch a field that silently stops participating in equality, such as one that was changed to a type without a proper ==.
Testing code that transforms models
The most useful model tests check functions that take a model and return a new one. Here is a small function and its tests:
Person birthday(Person p) => p.copyWith(age: p.age + 1);test('birthday returns an older copy and leaves the original alone', () {
const before = Person(name: 'Ada', age: 36);
final after = birthday(before);
expect(after, const Person(name: 'Ada', age: 37));
expect(before.age, 36);
expect(identical(before, after), isFalse);
});The assertions do three jobs. The first compares the whole object, so any unintended change to name or email fails the test. The second proves the input was not mutated. The third proves a new instance was returned.
One copyWith limit shows up in tests. In the usual generated form, passing null explicitly for a nullable field does clear it. Omitting the argument keeps the old value. Test both if your code clears optional fields:
test('copyWith can clear a nullable field', () {
const p = Person(name: 'Ada', email: '[email protected]');
expect(p.copyWith(email: null).email, isNull);
expect(p.copyWith(name: 'Ada L.').email, '[email protected]');
});Testing assertions
@Assert('age >= 0') runs when an instance is constructed, and only in debug mode and tests. Asserts are removed from release builds. To test it, build the object at runtime. A const expression with an invalid value is a compile-time error, so the test file would not compile.
test('negative age is rejected', () {
expect(
() => Person(name: 'Ada', age: -1),
throwsA(isA<AssertionError>()),
);
});JSON round trips
For a serializable model, the cheapest high-value test is a round trip. Convert a model to JSON and back, then compare it with the original. Also check one hand-written JSON map, because a round trip passes even if both directions share the same wrong key name.
test('toJson and fromJson round trip', () {
const p = Person(name: 'Ada', age: 36, email: '[email protected]');
expect(Person.fromJson(p.toJson()), p);
});
test('the e_mail key is used on the wire', () {
final p = Person.fromJson({
'name': 'Ada',
'age': 36,
'e_mail': '[email protected]',
});
expect(p.email, '[email protected]');
expect(p.toJson()['e_mail'], '[email protected]');
});
test('missing optional keys use defaults', () {
expect(Person.fromJson({'name': 'Ada'}), const Person(name: 'Ada'));
});For a model with nested freezed objects, toJson() returns the child objects by default. If you compare the result with a literal map, the test fails. Enable explicitToJson: true in @JsonSerializable or in build.yaml. Alternatively, round-trip through jsonEncode and jsonDecode, which calls each child's toJson for you.
Testing unions
For a sealed union, check two things: that each state equals an identical state, and that the states stay distinct from one another. Assume the LoadState union from the unions chapter.
test('union states compare by variant and payload', () {
expect(const LoadState.loading(), const LoadState.loading());
expect(LoadState.data(['a']), LoadState.data(['a']));
expect(LoadState.data(['a']), isNot(LoadState.data(['b'])));
expect(const LoadState.error('x'), isNot(const LoadState.loading()));
});
test('describe covers every state', () {
expect(describe(const LoadState.loading()), 'Loading');
expect(describe(LoadState.data(['a', 'b'])), '2 items');
expect(describe(const LoadState.error('boom')), 'Error: boom');
});The second test is where a new variant shows up. Adding a fourth constructor makes the switch in describe fail to compile until you handle it, so the compiler flags the missing case before the test does. Add a test line for the new variant at the same time.
When a test must check a specific variant, use isA:
expect(state, isA<LoadStateData>().having((s) => s.items, 'items', ['a']));Collections and nested models
Equality reaches into collection fields, so LoadState.data(['a']) equals another instance built from a different list with the same contents. Nested freezed objects work the same way, because each level uses its own generated ==. A nested update test therefore stays short:
test('copyWith.address updates only the city', () {
const user = User(name: 'Ada', address: Address(city: 'London'));
expect(
user.copyWith.address(city: 'Oslo'),
const User(name: 'Ada', address: Address(city: 'Oslo')),
);
});Common test problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Compile error about `_$Person` or a missing `.freezed.dart` file | Generated code was never built, or is not in the checkout | Run `dart run build_runner build --delete-conflicting-outputs` before `flutter test`. Do the same in CI. |
| Test fails but both printed objects look identical | A field holds an object with no `==`, or has a different runtime type | Give that type value equality, or make it a freezed class. |
| Test passes locally, fails after changing a field | Generated files are stale | Rebuild, or run `dart run build_runner watch` while developing. |
| Assertion test does not compile | The invalid value is in a `const` expression | Remove `const` and wrap the call in a closure. |
| Assertion test does not throw | Test run in release or profile mode | Run it with the default `flutter test`, which keeps asserts. |
Exercises
Exercise
A test builds two Person objects with the same name and age, and expect(a, b) passes. A teammate then changes the model so that name is a custom PersonName class with no == override. What happens to the test, and what are two ways to fix it?
Show answer
The test fails, because two separately built PersonName instances are compared by identity, so the Person objects are no longer equal. Fix it either by making PersonName a freezed class (or giving it == and hashCode), or by building both Person objects from the same PersonName instance. The first fix is the better one, because it restores value equality for every caller.
Exercise
Write a test that proves birthday(p) does not change p, using value equality and without checking any single field by name.
Show answer
Create const before = Person(name: 'Ada', age: 36); and a second const snapshot = Person(name: 'Ada', age: 36);. Call birthday(before), then expect(before, snapshot);. The test compares the whole object, so an accidental change to any field fails it. Because Person is immutable, the only realistic way for it to fail is if the code under test reaches the original through some other route.