MockMvc 测试:jsonPath,测试返回的每个元素是否包含子字符串

MockMvc testing : jsonPath, test every element returned contains substring

我正在进行集成测试,返回值是 json 个对象的数组。以下代码行匹配无误:

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

但是当我将 $[0].name 更改为 $[*].name 时出现错误

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"]>)

我一直在搜索,但没有找到答案...有没有办法检查每个 *.name 元素是否包含给定的子字符串?

这是因为 Matchers.containsString() 期望 String 输入,但 $[*].name returns net.minidev.json.JSONArrayArrayList.

您可以使用 Matchers.everyItem 来匹配列表:

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