使用 Hamcrest 和 JsonPath 进行 Spring MVC 测试:如何计算主体大小?(不计算会员)

Man*_*dan 5 json hamcrest spring-test-mvc

我正在与:

\n\n
    \n
  • Spring MVC 测试
  • \n
  • 汉克雷斯特
  • \n
  • Json路径
  • \n
\n\n

我有以下来自服务器的响应:

\n\n
MockHttpServletResponse:\n           Status = 200\n    Error message = null\n          Headers = {Content-Type=[application/json;charset=UTF-8]}\n     Content type = application/json;charset=UTF-8\n             Body = {\n  "id" : "100",\n  "nombre" : "Jes\xc3\xbas Voc\xc3\xaa",\n  "apellido" : "M\xc3\xa3o Nu\xc3\xb1ez",\n  "fecha" : "1977-12-08"\n}\n    Forwarded URL = null\n   Redirected URL = null\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下内容按预期工作(有效):

\n\n
 .andExpect(jsonPath("$").exists())\n .andExpect(jsonPath("$", notNullValue()))\n .andExpect(jsonPath("$", isA(LinkedHashMap.class)))\n\n .andExpect(jsonPath("$.*").exists())\n .andExpect(jsonPath("$.*", notNullValue()))\n .andExpect(jsonPath("$.*", isA(JSONArray.class)))\n .andExpect(jsonPath("$.*", hasSize(is(4))))\n
Run Code Online (Sandbox Code Playgroud)\n\n

我需要的测试("$")是 1。确认存在 1 项。兹再次确认以下事项:

\n\n
Body = {\n      "id" : "100",\n      "nombre" : "Jes\xc3\xbas Voc\xc3\xaa",\n      "apellido" : "M\xc3\xa3o Nu\xc3\xb1ez",\n      "fecha" : "1977-12-08"\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

我试过了:

\n\n
.andExpect(jsonPath("$", hasSize(is(1))))\n
Run Code Online (Sandbox Code Playgroud)\n\n

$观察和之间的区别$.*,对于后者我知道它计算字段的数量。但从前者我总是得到:

\n\n
java.lang.AssertionError: JSON path "$"\nExpected: a collection with size is <1>\n     but: was <{id=100, nombre=Jes\xc3\xbas Voc\xc3\xaa, apellido=M\xc3\xa3o Nu\xc3\xb1ez, fecha=1977-12-08}>\n    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18\n
Run Code Online (Sandbox Code Playgroud)\n\n

“似乎”数据不是一个集合,但请记住这.andExpect(jsonPath("$", isA(LinkedHashMap.class)))一点。我在某种程度上感到困惑。

\n\n

因此可能的测试是("$")1。?如果是,怎么办?

\n\n

我读过count Members with jsonpath?

\n\n

并说:

\n\n
\n

测试数组的大小: jsonPath("$", hasSize(4))

\n\n

计算对象的成员数: jsonPath("$.*", hasSize(4))

\n
\n\n

我返回的数据不是一个数组,而是一个数组,LinkedHashMap.class因为如果我使用.andExpect(jsonPath("$").isArray())我得到:

\n\n
java.lang.AssertionError: Expected an array at JSON path "$" but found: {id=100, nombre=Jes\xc3\xbas Voc\xc3\xaa, apellido=M\xc3\xa3o Nu\xc3\xb1ez, fecha=1977-12-08}\nExpected: an instance of java.util.List\n     but: <{id=100, nombre=Jes\xc3\xbas Voc\xc3\xaa, apellido=M\xc3\xa3o Nu\xc3\xb1ez, fecha=1977-12-08}> is a java.util.LinkedHashMap\n
Run Code Online (Sandbox Code Playgroud)\n\n

顺便说一句:.andExpect(jsonPath("$.*").isArray())通过。

\n

alf*_*lis 6

验证Map的大小而不是:

.andExpect(jsonPath("$", hasSize(1)))
Run Code Online (Sandbox Code Playgroud)

你应该使用:

.andExpect(jsonPath("$", aMapWithSize(1)))
Run Code Online (Sandbox Code Playgroud)

注意:使用 org.hamcrest.Matchers javadoc检查此链接

  • 我更新了链接...ManuelJordan 和 @D.Kastier 感谢您指出 (2认同)