问题描述
我想在Spring Boot中进行单元测试。这种情况是我有一个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,"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")
)
)
)