Man*_*dan 5 json hamcrest spring-test-mvc
我正在与:
\n\n我有以下来自服务器的响应:
\n\nMockHttpServletResponse:\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\nRun 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))))\nRun Code Online (Sandbox Code Playgroud)\n\n我需要的测试("$")是 1。确认存在 1 项。兹再次确认以下事项:
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 }\nRun Code Online (Sandbox Code Playgroud)\n\n我试过了:
\n\n.andExpect(jsonPath("$", hasSize(is(1))))\nRun Code Online (Sandbox Code Playgroud)\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\nRun Code Online (Sandbox Code Playgroud)\n\n“似乎”数据不是一个集合,但请记住这.andExpect(jsonPath("$", isA(LinkedHashMap.class)))一点。我在某种程度上感到困惑。
因此可能的测试是("$")1。?如果是,怎么办?
我读过count Members with jsonpath?
\n\n并说:
\n\n\n\n\n测试数组的大小: jsonPath("$", hasSize(4))
\n\n计算对象的成员数: jsonPath("$.*", hasSize(4))
\n
我返回的数据不是一个数组,而是一个数组,LinkedHashMap.class因为如果我使用.andExpect(jsonPath("$").isArray())我得到:
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\nRun Code Online (Sandbox Code Playgroud)\n\n顺便说一句:.andExpect(jsonPath("$.*").isArray())通过。
验证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检查此链接
| 归档时间: |
|
| 查看次数: |
4551 次 |
| 最近记录: |