Sub topic 12
Testing models with round trips
A round-trip test sends data through fromJson and toJson and checks that nothing changed on the way. This chapter shows what to assert, how to avoid false passes, and how to cover the edge cases generated code cannot decide for you.
It assumes you have the User, Order, and LineItem models from the earlier chapters, and that you know the basics of flutter_test. Replace my_app in the imports with your own package name.
What a round trip proves
The generated code is correct for the annotations you wrote. A test cannot find bugs in json_serializable. It finds mistakes in your annotations and in your assumptions about the server:
- A
@JsonKey(name: ...)that is misspelled. - A
fieldRenamethat does not match the real API. - A missing
explicitToJson. - A converter that loses precision.
- An enum value that the server spells differently.
A round trip also has limits. It proves that your model agrees with itself. It does not prove that the model agrees with the server. For that, start from a JSON sample the server actually sends.
| Test type | Starts from | Catches |
|---|---|---|
| Model round trip | A Dart object | Lossy `toJson`/`fromJson` pairs, converter bugs |
| Fixture round trip | A JSON literal | Wrong key names, wrong enum strings, wrong date formats |
| Failure test | Broken JSON | Missing required fields, unknown enum values |
| Default test | JSON with gaps | `defaultValue` and constructor defaults |
The basic test
The simplest test builds an object, encodes it to a string, decodes it, and compares:
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/models/user.dart';
void main() {
test('User survives a JSON round trip', () {
const user = User(id: 1, name: 'Ada', email: '[email protected]');
final json = jsonDecode(jsonEncode(user.toJson())) as Map<String, dynamic>;
final restored = User.fromJson(json);
expect(restored.id, user.id);
expect(restored.name, user.name);
expect(restored.email, user.email);
});
}Going through jsonEncode and jsonDecode matters. A direct call such as User.fromJson(user.toJson()) can pass even when the output holds values that JSON cannot represent, such as a DateTime object. Encoding to a real string and decoding it again reproduces what happens on the wire.
The test compares field by field because the generated classes do not define ==. Comparing two User objects with expect(restored, user) fails unless you add equality yourself, for example with package:equatable or a hand-written operator ==.
Compare maps instead of objects
You can often avoid writing == by comparing the JSON maps. The matcher equals compares maps and lists deeply. If a.toJson() equals b.toJson(), then the two objects carry the same serialized state.
test('restored User serializes to the same map', () {
const user = User(id: 1, name: 'Ada');
final restored = User.fromJson(
jsonDecode(jsonEncode(user.toJson())) as Map<String, dynamic>,
);
expect(restored.toJson(), equals(user.toJson()));
});This approach has a blind spot. If toJson drops a field, both sides drop it and the test still passes. A map comparison is only as strong as toJson, so pair it with the fixture tests below.
Start from a fixture
A fixture round trip starts from JSON that looks like the real API response. You decode it into a model, encode it back, and expect the original map. This checks the mapping in both directions against a fixed reference.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/models/order.dart';
const orderFixture = <String, dynamic>{
'order_id': 42,
'items': [
{'sku': 'A-1', 'quantity': 2},
{'sku': 'B-7', 'quantity': 1},
],
'created_at': '2024-05-01T10:30:00.000Z',
'status': 'cancelled_by_user',
};
void main() {
test('Order fixture decodes and re-encodes unchanged', () {
final order = Order.fromJson(orderFixture);
expect(order.orderId, 42);
expect(order.items, hasLength(2));
expect(order.items.first.sku, 'A-1');
expect(order.status, OrderStatus.cancelled);
expect(order.createdAt, DateTime.utc(2024, 5, 1, 10, 30));
expect(order.toJson(), equals(orderFixture));
});
}This single test covers several features at once:
fieldRename: FieldRename.snaketurnsorderIdintoorder_idin both directions.@JsonValue('cancelled_by_user')maps the string toOrderStatus.cancelled.- The
DateTimefield is read from and written as an ISO 8601 string. explicitToJson: trueturns the nestedLineItemobjects into maps.
The fixture uses a UTC timestamp ending in Z. A local DateTime serializes without the Z, so a fixture written in local time can pass on your machine and fail on a CI server in another time zone. Use UTC values in tests.
If you want realistic data, paste a captured API response into a file under test/fixtures/ and load it with File('test/fixtures/order.json').readAsStringSync(). Flutter runs tests with the project root as the working directory, so this relative path works.
Catching a missing explicitToJson
A missing explicitToJson is a bug that a round trip through jsonEncode can hide. The function jsonEncode calls toJson() on any object it cannot encode, so it quietly repairs nested objects that the generated toJson left as LineItem instances.
The map returned by toJson() itself still contains objects, not maps. That is why the fixture test above compares order.toJson() directly with equals(orderFixture), without encoding first. With the flag missing, the items list holds LineItem objects, the comparison fails, and you find out immediately.
test('nested items are plain maps, not objects', () {
final json = Order.fromJson(orderFixture).toJson();
expect(json['items'], isA<List<dynamic>>());
expect((json['items'] as List<dynamic>).first, isA<Map<String, dynamic>>());
});Keep both styles. The direct comparison checks the shape of the map. The string round trip checks that the result survives real encoding.
A reusable helper
When a project has many models, a small helper keeps the tests short:
import 'package:flutter_test/flutter_test.dart';
void expectStableJson<T>(
Map<String, dynamic> fixture,
T Function(Map<String, dynamic>) fromJson,
Map<String, dynamic> Function(T) toJson,
) {
expect(toJson(fromJson(fixture)), equals(fixture));
}
// Usage:
// expectStableJson(orderFixture, Order.fromJson, (o) => o.toJson());Use it only for fixtures that contain every field and no defaulted gaps. Fixtures with gaps need their own tests, covered next.
Testing defaults and optional fields
A fixture with a missing field will not come back unchanged. LineItem declares @JsonKey(defaultValue: 1) on quantity, so a payload without it decodes to 1, and toJson then writes quantity: 1. That asymmetry is correct. Test it as a separate case instead of forcing it into the round trip:
test('missing quantity defaults to 1 and is written back', () {
final item = LineItem.fromJson(const {'sku': 'A-1'});
expect(item.quantity, 1);
expect(item.toJson(), {'sku': 'A-1', 'quantity': 1});
});
test('null email is accepted for User', () {
final user = User.fromJson(const {'id': 7, 'name': 'Grace'});
expect(user.email, isNull);
});For nullable fields, also check what toJson writes. By default a null field appears as "email": null. If you set includeIfNull: false, the key is omitted. Pin whichever behavior your API expects.
Testing a JsonConverter
A converter is plain Dart, so test it on its own. You do not need a model.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/converters/epoch_millis_converter.dart';
void main() {
const converter = EpochMillisConverter();
test('DateTime round trips through epoch milliseconds', () {
final original = DateTime.utc(2024, 5, 1, 10, 30, 15, 250);
final restored = converter.fromJson(converter.toJson(original));
expect(restored, original);
expect(restored.isUtc, isTrue);
});
test('microseconds are lost, which is expected', () {
final original = DateTime.utc(2024, 5, 1, 10, 30, 15, 250, 999);
final restored = converter.fromJson(converter.toJson(original));
expect(restored.microsecond, 0);
});
}The second test records a limit of the format: epoch milliseconds cannot hold microseconds. A test that states the loss is better than a surprise in production.
Testing failure paths
Tests should cover bad input too. Without checked mode, the generated code fails with ordinary Dart errors:
test('missing required name throws', () {
expect(
() => User.fromJson(const {'id': 1}),
throwsA(isA<TypeError>()),
);
});
test('unknown enum string throws', () {
final bad = {...orderFixture, 'status': 'lost_in_space'};
expect(() => Order.fromJson(bad), throwsArgumentError);
});A null value cast to a non-nullable type throws a TypeError. An enum string that matches no value throws an ArgumentError. If you turn on checked: true, the generated code throws CheckedFromJsonException instead, and the exception names the offending key. Match your expectation to the mode you use.
How the pieces fit
The diagram shows where each kind of test sits on the path between the wire and the model.
Keeping the tests useful
- Run
dart run build_runner build --delete-conflicting-outputsbeforeflutter testin CI. A stale.g.dartfile makes tests pass against old code. - Keep one fixture per model, and update it when the API changes.
- Test the edges: an empty list, a null optional field, and an enum value at each end of the list.
- Write one failing-input test per required field that matters to you, not one per field.
Exercise
A test calls User.fromJson(user.toJson()) and passes. Name one problem this test could miss that User.fromJson(jsonDecode(jsonEncode(user.toJson()))) would catch.
Show answer
The direct call never encodes the data to a string, so values that JSON cannot represent, such as a raw DateTime or a nested model object left in the map, pass through unchanged and the test still passes. Encoding to a string and decoding it again forces the data to be valid JSON, as it would be on the wire.
Exercise
Write a test that checks OrderStatus.shipped serializes to the string 'shipped' inside an Order. Use orderFixture from this chapter.
Show answer
Build a new map with the status changed and compare the output: final json = {...orderFixture, 'status': 'shipped'}; final order = Order.fromJson(json); expect(order.status, OrderStatus.shipped); expect(order.toJson()['status'], 'shipped');
Exercise
Why does a fixture that omits quantity from a line item not round trip to an identical map, and how should you test that case?
Show answer
quantity has @JsonKey(defaultValue: 1), so the decoded item gets 1 and toJson writes quantity: 1, which the fixture did not contain. Test it as a separate default test: decode a map with only sku, then expect quantity to be 1 and toJson() to include 'quantity': 1.