我正在使用:
我有以下来自服务器的响应:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {
"id" : "100",
"nombre" : "Jesús Você",
"apellido" : "Mão Nuñez",
"fecha" : "1977-12-08"
}
Forwarded URL = null
Redirected URL = null
以下按预期工作(有效):
.andExpect(jsonPath("$").exists())
.andExpect(jsonPath("$", notNullValue()))
.andExpect(jsonPath("$", isA(LinkedHashMap.class)))
.andExpect(jsonPath("$.*").exists())
.andExpect(jsonPath("$.*", notNullValue()))
.andExpect(jsonPath("$.*", isA(JSONArray.class)))
.andExpect(jsonPath("$.*", hasSize(is(4))))
我需要测试("$")
是1.确认存在1项。它再次确认以下内容:
Body = {
"id" : "100",
"nombre" : "Jesús Você",
"apellido" : "Mão Nuñez",
"fecha" : "1977-12-08"
}
我试过了:
.andExpect(jsonPath("$", hasSize(is(1))))
观察$
和$.*
之间的区别,对于后者,我知道它会计算字段数。但从前者我总是得到:
java.lang.AssertionError: JSON path "$"
Expected: a collection with size is <1>
but: was <{id=100, nombre=Jesús Você, apellido=Mão Nuñez, fecha=1977-12-08}>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18
&#39;似乎&#39;数据不是集合,但要记住.andExpect(jsonPath("$", isA(LinkedHashMap.class)))
通过。我有点困惑。
因此可能测试("$")
是否为1?如果是,怎么样?。
我已阅读count members with jsonpath?
并说:
测试数组的大小:jsonPath(&#34; $&#34;,hasSize(4))
计算对象的成员:jsonPath(&#34; $。*&#34;,hasSize(4))
我返回的数据不是数组,而是LinkedHashMap.class
,因为如果我使用.andExpect(jsonPath("$").isArray())
,我会得到:
java.lang.AssertionError: Expected an array at JSON path "$" but found: {id=100, nombre=Jesús Você, apellido=Mão Nuñez, fecha=1977-12-08}
Expected: an instance of java.util.List
but: <{id=100, nombre=Jesús Você, apellido=Mão Nuñez, fecha=1977-12-08}> is a java.util.LinkedHashMap
BTW:.andExpect(jsonPath("$.*").isArray())
通过。