Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert two instances of JsonObject

Tags:

java

junit

This is the first time I'm trying to write my JUnit tests. In my case I need to validate a JSON response from an API with my expected JSON string. Part of my code looks like this:

@Test
public void test()
{
    String expected = "{\"b\":1}";
    HttpClient client = HttpClientBuilder.create().build();

    HttpPost request = new HttpPost("http://10.0.0.10/e/p");
    StringEntity params = new StringEntity("{\"a\":1}");

    request.addHeader("Content-Type", "application/json");
    request.setEntity(params);

    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();

    response.getStatusLine().getStatusCode();

    JsonObject actual   = readResponse(entity);
}

Now, you can see my expected value is a string. But, the actual value I am getting as JsonObject. Either I have to keep both into json string and assert them as json or I have to convert my actual value to JsonObject. I searched for both ways but couldn't figure out how. What/how would be the best fix for my case?

like image 205
Kamrul Khan Avatar asked Nov 25 '25 20:11

Kamrul Khan


2 Answers

You can build the expected JsonObject and compare it using assertEquals.

JsonObject expected = new JsonObject();
expected.addProperty("b", 1);

assertEquals(expected, actual);
like image 105
Stefan Birkner Avatar answered Nov 27 '25 10:11

Stefan Birkner


You can use JsonUnit library.

It allows assertions in a way you look for:

JsonObject actual  = readResponse(entity)
// objects are automatically serialized before comparison
assertJsonEquals("{\"b\":1}", actual);

but it also supports comparing two objects that represent JSON element internally:

JsonObject actual = new JsonObject();
actual.addProperty("test", 1);
JsonObject expected = new JsonObject();
expected.addProperty("test", 1);
assertJsonEquals(expected, actual);

Framework has support for both Jackson and Gson and support for Hamcrest matchers.

like image 44
bbelovic Avatar answered Nov 27 '25 10:11

bbelovic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!