Test JSON with a few lines of code

JSONassert helps you writing JSON unit tests

You have to write a unit test and JSON is involved. Usually this will end up in a lot of lines of code. You know the situation, I bet.

Here JSONassert comes into play. It allows to write JSON unit tests with just a few lines of code. For example checking an JSON object:

[code]
book = new Book();
book.setName("The book");

String result = BookUtils.toJson(book);
boolean strict = false;
JSONAssert.assertEquals("{\"name\":\"The book\"}", result, strict);
[/code]

The strictMode == false makes ordering not relevant and makes your test less brittle.

JSONassert comes with JSONCompareResult. I thinks this class is very handy when you are interested in a particular aspect like a missing field or value.

[code]

JSONCompareResult result =
JSONCompare.compareJSON("{\"name\":\"The book\",\"pages\":100}",
"{\"name\":\"The book\"}", JSONCompareMode.LENIENT);
assertTrue(result.isMissingOnField());
assertEquals(result.getFieldMissing().size(), 1);
FieldComparisonFailure fieldComparisonFailure = result.getFieldMissing().get(0);
assertEquals("pages",fieldComparisonFailure.getExpected());
[/code]

JSONCompareResult provides a list of missing fields and fields with errors. Depending on your case, you can easily determine which field makes trouble.

JSONassert is a real cool third library. I like it!

GitHub-Mark-32px On Github you find more examples.

 

Resources

http://jsonassert.skyscreamer.org/quickstart.html
http://jsonassert.skyscreamer.org/apidocs/index.html
https://github.com/skyscreamer/JSONassert

Consent Management Platform von Real Cookie Banner