Sub topic 12
Testing Models with JSON Round Trips
This chapter assumes you know Dart classes, null safety, Map<String, dynamic>, Flutter tests, and the json_serializable setup from earlier chapters. A round-trip test checks that a model can be encoded to JSON and decoded back without losing meaningful data.
What a Round Trip Tests
A model normally crosses two boundaries:
- An API response becomes a Dart object with
fromJson. - A Dart object becomes an API request or stored value with
toJson.
A round-trip test exercises both directions:
User object → toJson → JSON text → jsonDecode → fromJson → User objectThe JSON text step matters because it catches values that look valid as Dart maps but cannot actually be represented as JSON.
A successful test should compare fields, not object identity. The original and restored objects are different instances, so original == restored is usually false unless you implement value equality.
Writing a Basic Round-Trip Test
Create a test file such as test/user_test.dart. This example assumes the generated user.g.dart file exists and that User has id, name, and nullable email fields.
import 'dart:convert';
import 'package:flutter_test/flutter_test.dart';
import 'package:your_app/user.dart';
void main() {
test('User survives a JSON round trip', () {
const original = User(
id: 1,
name: 'Ada',
email: '[email protected]',
);
final jsonText = jsonEncode(original.toJson());
final decoded = jsonDecode(jsonText) as Map<String, dynamic>;
final restored = User.fromJson(decoded);
expect(restored.id, original.id);
expect(restored.name, original.name);
expect(restored.email, original.email);
});
}Run the test with:
flutter test test/user_test.dartjsonEncode converts the map into a JSON string. jsonDecode returns dynamic, so the cast confirms that the response has the object shape expected by User.fromJson.
What to Test
Test values that often reveal mapping mistakes:
- Nullable fields set to both
nulland a real value. - Empty lists and lists containing several objects.
- Enum values, especially values using
@JsonValue. - Date and time fields.
- Default values for missing fields.
- Snake-case keys configured with
fieldRename. - Custom
JsonConvertertypes.
A test that only uses ordinary, non-null values can pass while the production model still fails for an omitted field or a special enum value.
| Test case | Failure it can reveal |
|---|---|
| Nullable field is `null` | Incorrect null handling |
| Empty nested list | Incorrect collection conversion |
| Every enum value | Wrong JSON enum value |
| Custom date value | Incorrect converter logic |
| Missing optional key | Incorrect default configuration |
Testing Invalid Input
Round trips cover valid data. Add separate tests for malformed or incomplete payloads. For example, verify that a required integer is not silently accepted as a string, or that a missing required key produces an error when checked deserialization is enabled.
Keep these tests separate from round-trip tests. One test should answer one question: whether valid data survives conversion, or whether invalid data is rejected.
Exercise
Why should a round-trip test compare fields instead of using expect(restored, original)?
Show answer
fromJson creates a new object instance. Two instances are not equal by identity unless the model defines value equality, so field comparisons verify the restored data directly.