JsonPatchApplier { public JsonNode apply(JsonNode document, List<PatchOperation> patchOperations) throws PatchApplicationException { try { JsonNode patch = mapper.convertValue(patchOperations, JsonNode.class); JsonPatch jsonPatch = JsonPatch.fromJson(patch); return jsonPatch.apply(document); } catch (IOException | JsonPatchException e) { String message = String.format("Unable to apply patch to document. document: %s, patch: %s", document, patchOperations); throw new PatchApplicationException(message, e); } }  JsonNode apply(JsonNode document, List<PatchOperation> patchOperations);  }
@Test public void createRoad() throws Exception { JsonNode road = mapper.readTree("{\"name\":\"road1\"}"); List<PatchOperation> operations = singletonList(PatchOperation.add("", road)); JsonNode result = underTest.apply(NullNode.getInstance(), operations); assertThat(result.isMissingNode(), is(false)); assertThat(result.path("name").textValue(), is("road1")); }
@Test public void removeRoad() throws Exception { JsonNode road = mapper.readTree("{\"name\":\"road1\"}"); List<PatchOperation> operations = singletonList(PatchOperation.remove("")); JsonNode result = underTest.apply(road, operations); assertThat(result.isMissingNode(), is(true)); }
@Test public void addDescription() throws Exception { JsonNode road = mapper.readTree("{}"); List<PatchOperation> operations = singletonList(PatchOperation.add("/description", "description1")); JsonNode result = underTest.apply(road, operations); assertThat(result.isMissingNode(), is(false)); assertThat(result.get("description").textValue(), is("description1")); }
@Test public void updateDescription() throws Exception { JsonNode road = mapper.readTree("{\"description\":\"description1\"}"); List<PatchOperation> operations = singletonList(PatchOperation.replace("/description", "description2")); JsonNode result = underTest.apply(road, operations); assertThat(result.isMissingNode(), is(false)); assertThat(result.get("description").textValue(), is("description2")); }
@Test public void removeDescription() throws Exception { JsonNode road = mapper.readTree("{\"description\":\"description1\"}"); List<PatchOperation> operations = singletonList(PatchOperation.remove("/description")); JsonNode result = underTest.apply(road, operations); assertThat(result.isMissingNode(), is(false)); assertThat(result.get("description"), is(nullValue())); }
@Test(expected = PatchApplicationException.class) public void throwsPatchApplicationExceptionWhenNotAValidPatch() throws Exception { JsonNode road = mapper.readTree("{\"description\":\"description1\"}"); List<PatchOperation> operations = singletonList(PatchOperation.replace("/description", "description2")); JsonNode jsonNodePatch = mapper.readTree("{}"); ObjectMapper mockObjectMapper = mock(ObjectMapper.class); when(mockObjectMapper.convertValue(any(), eq(JsonNode.class))).thenReturn(jsonNodePatch); underTest = new JsonPatchApplier(mockObjectMapper); underTest.apply(road, operations); }