Using Spring's mockMvc, how do I check if the returned data contains part of a string?
Solution 1
Looks like you can pass a Hamcrest Matcher instead of a string there. Should be something like:
mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andExpect(content().string(org.hamcrest.Matchers.containsString("{\"id\":\"" + id + "\"}")));
Solution 2
A more appropriate way to do that is:
mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", org.hamcrest.Matchers.is(id)));
Solution 3
I know it's been too many years, but still, I hope my answer can be useful for someone =)
When I need to check if a json value form a response contains some string I use containsString
method:
mockMvc.perform(post("/url")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.andExpect(status().isOk())
.andExpect(jsonPath("$.field1").value(value1))
.andExpect(jsonPath("$.field2", containsString(value2)));
Solution 4
Another way you can get to the String respone of a mockMVC requst so you can compare or manipulate it in other ways is as follows:
MvcResult result = mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andReturn();
String stringResult = result.getResponse().getContentAsString();
boolean doesContain = stringResult.contains("{\"id\":\"" + id + "\"}");
You could also wrap the whole thing in an assertTrue while still using String methods:
assertTrue(mockMvc.perform(get("/api/users/" + id))
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString()
.contains("{\"id\":\"" + id + "\"}");
I prefer the approved answer, just thought I would submit this as another alternative.
Related videos on Youtube
Dave
Updated on July 09, 2022Comments
-
Dave almost 2 years
I’m using Spring 3.2.11.RELEASE and JUnit 4.11. Using the Spring mockMvc framework, how do I check if a method returning JSON data contains a particular JSON element? I have
mockMvc.perform(get("/api/users/" + id)) .andExpect(status().isOk()) .andExpect(content().string("{\"id\":\"" + id + "\"}"));
but this checks for an exact match against the string returned and I’d rather check if the JSON string contains the value contained by my local field “id”.