Testing JSON Objects for Equality while Ignoring Child Order in Java
In unit testing, it is common to compare JSON objects returned from web services to expected values. However, some JSON libraries might perform strict reference comparisons, which can be brittle and fail due to differences in child order.
For this purpose, the Skyscreamer JSONAssert library provides a solution. Its non-strict mode allows for flexibility by:
In contrast, strict mode behaves more conservatively, similar to json-lib's test class.
To utilize JSONAssert, tests can be constructed as follows:
@Test
public void testGetFriends() {
JSONObject data = getRESTData("/friends/367.json");
String expected = "{friends:[{id:123,name:\"Corby Page\"}"
",{id:456,name:\"Solomon Duskis\"}]}";
JSONAssert.assertEquals(expected, data, false); // Non-strict mode
}
The parameters in JSONAssert.assertEquals() include the expected JSON string, actual data string, and a flag indicating strict mode or not.
JSONAssert provides clear error messages, which is crucial when comparing large JSON objects, ensuring robustness in unit testing.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3