Using Spring's mockMvc, how do I check if the returned data contains part of a string? Using Spring's mockMvc, how do I check if the returned data contains part of a string? json json

Using Spring's mockMvc, how do I check if the returned data contains part of a string?


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 + "\"}"))); 


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)));


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.