Java EE 8 and JSON-P Simplify System Testing with JSON Patch 📎
JSON-P (JSR-374) from Java EE 8 comes with JSON Patch support, which is useful for system testing.
A JSON object returned from a HTTP endpoint can be easily compared to a local representation loaded from a file:
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonPatch;
import javax.json.JsonReader;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class JSONPDiffTest {
@Test
public void subtraction() {
//e.g. server result
JsonObject actual = Json.createObjectBuilder().
add("a", 21).
add("b", 1).
build();
try (JsonReader reader
= Json.createReader(this.getClass().getResourceAsStream("/expected.json"))) {
JsonObject expected = reader.readObject();
JsonPatch diff = Json.createDiff(expected, actual);
assertTrue(diff.toString(), diff.toJsonArray().isEmpty());
}
}
}
The code above loads the file src/test/resources/expected.json
with the content:
{
"a": 21,
"b": 2
}
and compares it to the actual
instance.
The result is:
java.lang.AssertionError: [{"op":"replace","path":"/b","value":1}]
JSON-P comes as a single maven dependency:
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.json</artifactId>
<version>1.1.2</version>
</dependency>
See you at Java EE Workshops at MUC Airport, particularly at the Java EE CI/CD, Testing and Quality workshop