无法将 json 数组元素与值匹配

Cannot match the json array element to the value

我想在 spring 启动时进行单元测试。情况是我有一个 JSON 数组,我必须检查每个数组字段“详细信息”是否等于“T”或“S”(仅接受“T”或“S”)。但是,当我使用 Jsonpath & anyof 时。它给我一个断言错误,任何解决方案都可以测试它吗?谢谢

@Test
public void test() throws Exception {
    mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(jsonPath("$..records[*].abc.details",anyOf(is("T"),is("S"))))
}

这是json

{
  "records": [
    {
      "id": 1,
      "abc": {
        "details": "T",
        "create-date": "2016-08-24T09:36"
      }
    },
    {
      "id": 5,
      "abc": {
        "detail-type": "S",
        "create-date": "2012-08-27T19:31"
      }
    },
    {
      "id": 64,
      "abc": {
        "detail-type": "S",
        "create-date": "2020-08-17T12:31"
      }
    }
  ]
}

您似乎将字符串 "T""S" 与 JSONArray 的实例进行了比较。尝试以下匹配器:

MockMvcResultMatchers.jsonPath(
    "$..records[*].abc.details", 
    Matchers.anyOf(
        Matchers.hasItem("T"), 
        Matchers.hasItem("S")
    )
)

更新:

根据您的评论,如果 details 包含其他内容然后 "T""S",您希望测试失败。只需将另一个匹配器传递给 jsonPath()Here 您可以找到使用集合的匹配器示例。在您的特定情况下,匹配器可能如下所示:

MockMvcResultMatchers.jsonPath(
    "$..records[*].abc.details", 
    Matchers.everyItem(
        Matchers.anyOf(
            Matchers.is("T"),
            Matchers.is("S")
        )
    )
)