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?
You can build the expected JsonObject and compare it using assertEquals.
JsonObject expected = new JsonObject();
expected.addProperty("b", 1);
assertEquals(expected, actual);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With