Member-only story

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));
}

The test will be failed with this error:

java.lang.AssertionError: 
Expected: <{"id":1,"name":"saeed","posts":[1,2,3,4]}>
got: <{"posts":[4,2,1,3],"name":"saeed","id":1}>

This is because in this test we called the toString method of the JsonObject. the JSON libraries like Gson or Jackson produce different String formats for these two JsonObjects .

What is the solution?

In such a scenario, I use the JSONassert library:

<dependency>
<groupId>org.skyscreamer</groupId>
<artifactId>jsonassert</artifactId>
<version>1.5.0</version>
<scope>test</scope>
</dependency>

This library can handle this kind of problem easily:

@Test
public void test_json_using_json_assert() throws JSONException {
JSONAssert.assertEquals(expectedJsonObj.toString(), actualJsonObj.toString()…

--

--

Saeed Zarinfam
Saeed Zarinfam

Written by Saeed Zarinfam

✍️ I write about Software Development, including Java, Go, Spring, Containers, K8s, AI, Observability, and more ⋈

No responses yet

Write a response