# JsonAssert

<http://www.baeldung.com/jsonassert>

[JSONAssert librar](http://jsonassert.skyscreamer.org/) – a library focused on understanding JSON data and writing complex [JUnit](http://junit.org/junit4/) tests using that data.

## 1. LENIENT mode

eg1:

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

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

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

As we can see, the*real\_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:

```java
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:

```java
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);
```
