JsonAssert

http://www.baeldung.com/jsonassert

JSONAssert librar – a library focused on understanding JSON data and writing complex JUnit tests using that data.

1. LENIENT mode

eg1:

String actual = "{id:123, name:\"John\"}";
JSONAssert.assertEquals(
  "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);

The comparison mode LENIENT means that even if the actual JSON contains extended fields, the test will still pass:

String actual = "{id:123, name:\"John\", zip:\"33025\"}";
JSONAssert.assertEquals(
  "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);

As we can see, thereal_variable contains an additional field_zip_which is not present in the expected_String. Still, the test will pass.

This concept is useful in the application development. This means that our APIs can grow, returning additional fields as required, without breaking the existing tests.

2. STRICT Mode

The behavior mentioned in the previous sub-section can be easily changed by using the _STRICT _comparison mode:

eg2:

String actual = "{id:123,name:\"John\"}";
JSONAssert.assertNotEquals(
  "{name:\"John\"}", actual, JSONCompareMode.STRICT);

3. Using a Boolean Instead of JSONCompareMode

The compare mode can also be defined by using an overloaded method that takes boolean _instead of _JSONCompareMode _where _LENIENT = false _and _STRICT = true:

eg3:

String actual = "{id:123,name:\"John\",zip:\"33025\"}";
JSONAssert.assertEquals(
  "{id:123,name:\"John\"}", actual, JSONCompareMode.LENIENT);
JSONAssert.assertEquals(
  "{id:123,name:\"John\"}", actual, false);

actual = "{id:123,name:\"John\"}";
JSONAssert.assertNotEquals(
  "{name:\"John\"}", actual, JSONCompareMode.STRICT);
JSONAssert.assertNotEquals(
  "{name:\"John\"}", actual, true);

Last updated