Json and beyond
  • Introduction
  • JsonView
  • JsonPath
  • JsonAssert
  • Gson
  • Jackson
  • JSON.simple
  • serialization/deserialization
Powered by GitBook
On this page
  • 1. LENIENT mode
  • 2. STRICT Mode
  • 3. Using a Boolean Instead of JSONCompareMode

Was this helpful?

JsonAssert

PreviousJsonPathNextGson

Last updated 5 years ago

Was this helpful?

– a library focused on understanding JSON data and writing complex 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);
http://www.baeldung.com/jsonassert
JSONAssert librar
JUnit