How to compare two JSON objects in Java tests and when the order of values is not important
Compare two big JSON objects in Java tests easily
When I am writing tests to confirm the JSON structure generated in the API with the expected structure, I almost always prefer to use the JSON path for this job, but In some scenarios, you can’t use the JSON path and write one assertion for each field in the expected JSON result, for example when your API produces a very large JSON response. In these cases, maybe it is a good idea to have the expected JSON output in a file and then compare the produced JSON result with that to confirm that the result is identical to the content of the expected JSON file.
∘ So what is the problem?
∘ What is the solution?
· Final Thoughts
So what is the problem?
The problem occurs when the produced JSON structure by the API is the same as expected, but the order of the entities inside of the result is not the same (Similar to the image below).
In these scenarios, you can’t use a simple JUnit assertion to compare the String format of your JsonObject
:
@Test
public void test_json_using_gson() {
Assert.assertThat(actualJsonObj, equalTo(expectedJsonObj));
}