Search code examples
spring-bootintegration-testingjsonpathmockmvc

MockMvc testing : jsonPath, test every element returned contains substring


I'm doing an integration test, and the returned value is an array of json objects. The following line of code matches without error:

        mockMvc.perform(MockMvcRequestBuilders.get(uri)
            .param("name", text)
            .accept(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$[0].name", Matchers.containsString("div3")));

but when I change $[0].name to $[*].name I get an error

java.lang.AssertionError: JSON path "$[*].name"
Expected: a string containing "div3"
 but: was a net.minidev.json.JSONArray (<["Testing Custom Searches div3: 1","Testing Custom Searches div3: 4","Testing Custom Searches div3: 7","Testing Custom Searches div3: 10","Testing Custom Searches div3: 13","Testing Custom Searches div3: 16","Testing Custom Searches div3: 19"]>)

I've been searching around, and not finding an answer...is there a way to check that every *.name element contains a given substring?


Solution

  • This is because Matchers.containsString() expect a String input but $[*].name returns a net.minidev.json.JSONArray which is an ArrayList.

    You can use Matchers.everyItem to match against a list:

    MockMvcResultMatchers.jsonPath("$[*].name", Matchers.everyItem(Matchers.containsString("div3")))