【发布时间】:2017-01-21 06:25:26
【问题描述】:
我正在与:
- Spring MVC 测试
- Hamcrest
- JsonPath
我有以下来自服务器的响应:
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
“似乎”数据不是集合,但请记住 .andExpect(jsonPath("$", isA(LinkedHashMap.class))) 传递。不知怎的,我很困惑。
因此可能测试("$") 为1。?如果是,如何?
我读过count members with jsonpath?
然后说:
测试数组大小:jsonPath("$", hasSize(4))
统计对象的成员数:jsonPath("$.*", 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
顺便说一句:.andExpect(jsonPath("$.*").isArray()) 通过。
【问题讨论】:
-
我需要测试 ("$") 是否为 1。确认存在 1 项。我已经重读了几次,但仍然无法理解。
1到底是什么意思? -
下面的
Body = { "id" : "100", "nombre" : "Jesús Você", "apellido" : "Mão Nuñez", "fecha" : "1977-12-08" }只是一项,有四个字段。因此$.*表示具有四个字段的项目。但我需要测试该项目(我认为$应该足够但失败了)。 -
嗯,那么
jsonPath("$").exists()有什么问题呢? -
是有效的,如果可以的话,只是古玩。如果结果返回两个项目会发生什么。
jsonPath("$").exists()也应该通过,但它不在乎是 1 项还是 2 项。 -
但是如何一次获得两个以上的 JSON 项作为根?它应该由于语法错误或其他原因而失败,但无论如何这一定是非法的。
标签: json hamcrest spring-test-mvc