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

Dave picture Dave · May 17, 2016 · Viewed 19.6k times · Source

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”.

Answer

unigeek picture unigeek · May 18, 2016

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