![](http://www.baeldung.com/wp-content/uploads/2024/11/Testing-Featured-Image-02-1024x536.jpg)
1. Overview
In this short article, we’ll explore the JsonUnit library and use it to create expressive assertions for JSON objects. We’ll start with a simple example, showcasing the smooth integration between JsonUnit and AssertJ.
After that, we’ll learn how to verify JSON against a templated String. This approach offers flexibility and allows us to use custom placeholders to match element values against a wide range of criteria or to ignore specific JSON paths entirely.
2. Getting Started
The JsonUnit project contains a few different modules that can be imported independently. The json-unit-assertj module is the recommended way of using the library, providing a fluent API and a smooth integration with the AssertJ library.
Let’s add this dependency to our pom.xml:
<dependency>
<groupId>net.javacrumbs.json-unit</groupId>
<artifactId>json-unit-assertj</artifactId>
<version>3.5.0</version>
<scope>test</scope>
</dependency>
The library assumes a JSON deserializer is already in our classpath and automatically tries to use it. Currently, the supported integrations are Gson, org.json, Moshi, and Jackson2.
We can now create an assertion object using the static factory method assertThatJson(). Consequently, we’ll be able to use JsonUnit’s fluent API to validate that the tested JSON is a valid JSON object and verify its key-value pairs:
@Test
void whenWeVerifyAJsonObject_thenItContainsKeyValueEntries() {
String articleJson = """
{
"name": "A Guide to Spring Boot",
"tags": ["java", "spring boot", "backend"]
}
""";
assertThatJson(articleJson)
.isObject()
.containsEntry("name", "A Guide to Spring Boot")
.containsEntry("tags", List.of("java", "spring boot", "backend"));
}
JsonUnit allows us to easily navigate through the JSON object while leveraging AssertJ’s powerful assertions for verifications. For example, we can use methods like node() to navigate the JSON and isArray() to access an API tailored for asserting collections:
assertThatJson(articleJson)
.isObject()
.containsEntry("name", "A Guide to Spring Boot")
.node("tags")
.isArray()
.containsExactlyInAnyOrder("java", "spring boot", "backend");
On the other hand, we can compare the tested object to a plain JSON String in a declarative fashion. To do this, we just need to wrap the expected content within an ExpectedNode instance, which can be done using the function JsonAssertion.json():
assertThatJson(articleJson)
.isObject()
.isEqualTo(json("""
{
"name": "A Guide to Spring Boot",
"tags": ["java", "spring boot", "backend"]
}
"""));
3. Supported Features
The library offers many features like navigating complex JSON paths, ignoring fields or values, and asserting against custom matchers or regex patterns. Although we won’t discuss every feature, we’ll explore some key ones.
3.1. Options
JsonUnit enables us to define various configurations for each assertion. We can find the supported features in the Option enum and enable them via the when() method.
Let’s enable the IGNORE_ARRAY_ORDER and IGNORE_EXTRA_ARRAY_ITEMS options for an alternative way of verifying that the JSON contains the tags “java” and “backend” in any order:
assertThatJson(articleJson)
.when(Option.IGNORING_ARRAY_ORDER)
.when(Option.IGNORING_EXTRA_ARRAY_ITEMS)
.node("tags")
.isEqualTo(json("""
["backend", "java"]
"""));
3.2. Placeholders
When verifying JSON output against expected content, the library allows the expected result to be templated. For example, placeholders like ${json-unit.any-string} and ${json-unit.ignore-element} can validate the article’s name as a string while ignoring its list of tags:
assertThatJson(articleJson)
.isEqualTo(json("""
{
"name": "${json-unit.any-string}",
"tags": "${json-unit.ignore-element}"
}
"""));
Similarly, we can use placeholders like ${json-unit.any-number}, ${json-unit.any-boolean}, ${json-unit.regex}, or even create custom placeholders tailored to specific use cases.
3.3. Ignoring Paths
So far, we’ve learned how to use a placeholder to ignore an element of the JSON object. However, we can also leverage the whenIgnoringPaths() method to define the JSON paths to be ignored when performing the assertions:
assertThatJson(articleJson)
.whenIgnoringPaths("tags")
.isEqualTo(json("""
{
"name": "A Guide to Spring Boot",
"tags": [ "ignored", "tags" ]
}
"""));
}
As we can see, when we use whenIgnoringPaths(“tags”) the assertion passes even if the two JSON objects have different values for the tags key.
4. Conclusion
In this hands-on tutorial, we discussed the basics of JsonUnit and explored its API for creating fluent and declarative assertions, making JSON validation simple and expressive.
We also learned how to verify JSON content by comparing it to a templated String. This technique proves especially powerful when paired with other library features, such as configuration Options, custom placeholders, and type matchers.
As always, the code for the article is available over on GitHub.