In an API project, I'm consolidating data from separate external sources. One of these sources returns data in JSON format.
{
"agency": "SomeAgency",
"agencyData": {
"brandColor": "#A70000",
"cityName": "",
"countryCode": "BE",
"email": "",
"iataCode": "12345678",
"imageUrl": "",
"name": "",
"phoneContact": "",
"postalCode": "",
"stateProv": "",
"street": ""
},
"agent": "[email protected]",
"agentEmail": "[email protected]",
"allowedPassengerUpdates": {
"document_correction": {
"allowed": true,
"allowedPerPassengerType": {
"ADT": true
},
"fieldsToUpdate": [
"documentID",
"documentType",
"fiscalName",
"citizenshipCountryCode",
"residenceCountryCode",
"issuingCountryCode",
"expirationDate"
]
},
...
I serialize this data into an object model, and use this model for the actual consolidation.
To validate this, I wrote the following unit test:
public void IsJsonValid()
{
var expectedJson = LoadJson("Example.json");
// Generate a base object model using a generalized structure
var expected = JToken.Parse(expectedJson);
// Generating an object model using the defined classes
var actualModel = JsonConvert.DeserializeObject(expectedJson);
// Converting the new object back into json
var actualJson = JsonConvert.SerializeObject(actualModel);
// Generating a new object using a generalized structure
var actual = JToken.Parse(actualJson);
// Comparing the 2
actual.Should().BeEquivalentTo(expected);
}
This approach works fine if the data provider keeps its JSON clean and doesn't start mixing data types throughout the file.
When I execute the test, the comparison (actual.Should().BeEquivalentTo(expected)) throws an exception:

The exception more in detail:

What should I do differently to avoid this issue?
Olivier MuhringPosted Jun 7, 2024, 11:02 AM
The problem is the original json is complicated and rather large... I wanted to validate the model actually reflects what's inside it.
That's why I compared it in my roundabout way...
It's not perfect, though. In another case, some fields contain a mix of ints and floats.
You'd have an array of objects, where each object contains a field BasePrice... but depending ion where the original data originates from, it gets shown as an int in 1 case, as a float in another.
Which makes the test fails since it expects all fields to be similar..
But here it seems to be an issue with FluentAssertions...
Tuhin PaulPosted Jun 6, 2024, 4:51 PM
Instead of comparing the entire JSON object, you can explicitly assert on specific properties that are crucial for your data consolidation logic. This approach gives you more control over what's being validated.+
Tuhin PaulPosted Jun 6, 2024, 4:51 PM
Libraries like FluentAssertions or Json.NET's
JsonConvert.DeepEqualsmethod can handle structural comparisons of JSON objects. These libraries consider objects with the same properties and values to be equal even if the formatting differs (e.g., whitespace, order of properties).