Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
badperson Avatar asked Mar 10 '26 21:03

badperson


1 Answers

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")))
like image 55
Dickson Avatar answered Mar 13 '26 13:03

Dickson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!