Detailed explanation of the technical principles of the "JSON Unit" framework in the Java library
JSON Unit is a Java class library for testing and asserting JSON data.It provides a set of methods and tools for processing JSON data, which can simplify the work of comparing, verifying and asserting JSON data during the test.
JSON Unit's technical principles mainly involve the following aspects:
1. JSON data conversion: JSON Unit provides the function of converting the Java object into a JSON format string to facilitate comparison and asserting JSON data during the test process.It uses the Jackson library or JSONB library in Java for JSON data conversion and analysis.
Example code:
MyObject myObject = new MyObject();
String jsonString = JsonUtils.toJson(myObject);
2. JSON comparison and assertion: JSON Unit provides a series of assertions to compare whether the two JSON data are equal.It supports a flexible comparison of each part of JSON data, including key values, array, nested objects, etc.Through these assertions, developers can easily test and verify JSON data.
Example code:
String expectedJson = "{\"name\": \"John\", \"age\": 30}";
String actualJson = "{\"name\": \"John\", \"age\": 30}";
JsonAssert.assertJsonEquals(expectedJson, actualJson);
3. JSON path and filtering: JSON Unit supports fragments that use the JSON path and filter to select and operate JSON data.Developers can use the JSON path expression to locate the specific part of the JSON data, and then assert or other operations.
Example code:
String json = "{\"name\": \"John\", \"age\": 30, \"address\": {\"city\": \"New York\", \"street\": \"123 Main St\"}}";
JsonPathAssert.assertThat(json).hasJsonPath("$.name").isEqualTo("John");
JsonPathAssert.assertThat(json).hasJsonPath("$.address.city").isEqualTo("New York");
4. Custom assertion and configuration: JSON Unit allows developers to customize assertions and configurations to meet specific test needs.Developers can write their own assertions, or define the expected JSON data and assertive rules by configure files.
Example code:
AssertJConfiguration.customization().withGsonConfiguration(c -> {}).registCustomization();
SoftAssertions.assertSoftly(softly -> {
softly.assertThatJson("{\"name\": \"John\", \"age\": 30}").isEqualTo("{\"name\": \"John\"}");
softly.assertThatJson("{\"name\": \"John\", \"age\": 30}").node("age").isNumber();
});
In short, JSON Unit provides a convenient and flexible way to test and asserts JSON data.It provides a series of methods and tools to simplify the process of asserting and verifying JSON data in the test process, and also supports custom assertions and configurations to meet the specific needs of developers.