I test my json api like that:
void testJsonCompareMode() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.post("/api/test")
.content("{\"hello\":\"world\"}")
.contentType(org.springframework.hateoas.MediaTypes.HAL_JSON_VALUE))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.somePath").value(
Matchers.equalTo(JsonPath.parse("[{\"value\": 123}]").json())
));
}
I put expected json there as string. Like in this case [{"value": 123}]
. I would like to be able to use JSONCompareMode functionality. Currently it seems to work like a STRICT but I would like to get it to work like NON_EXTENSIBLE.
To do this I wanted to implement my own matcher:
private static class JsonMatcher extends org.hamcrest.TypeSafeMatcher<String> {
private final String expectedJson;
private final JSONCompareMode mode;
public JsonMatcher(String expectedJson, JSONCompareMode mode) {
this.expectedJson = expectedJson;
this.mode = mode;
}
@Override
protected boolean matchesSafely(String actualJson) {
try {
JSONCompareResult result = JSONCompare.compareJSON(expectedJson, actualJson, mode);
return result.passed();
} catch (JSONException e) {
return false;
}
}
@Override
public void describeTo(org.hamcrest.Description description) {
description.appendText(expectedJson);
}
}
and then use it like:
.andExpect(jsonPath("$._embedded.somePath").value(
new JsonMatcher("[{\"value\": 123}]", JSONCompareMode.NON_EXTENSIBLE)
));
But it always goes to describeTo method and not matchesSafely. After trying many times I could not get it to work. What is the correct way of doing this?