Spring测试和JsonPath问题

Mik*_*ike 8 spring-mvc jsonpath

我遇到了测试和json路径的问题

我只是尝试执行一个简单的测试并检查id的值:

mockMvc.perform(get("/applications/")).andExpect(status().isOk())
       .andDo(print())
       .andExpect(content().contentType(TestUtils.APPLICATION_JSON_UTF8))
       .andExpect(jsonPath("$", hasSize(4)))
       .andExpect(jsonPath("$.id",is(1)));
Run Code Online (Sandbox Code Playgroud)

但是我收到如下错误.好像我的代码应该检查id值.我不够具体,因为返回的JSON中有多个项目?任何帮助表示赞赏.谢谢.

     Content type = application/json;charset=UTF-8
             Body = [{"id":1,"name":"test2"},{"id":2,"name":"test2"}]
   Forwarded URL = null
   Redirected URL = null
          Cookies = []

java.lang.AssertionError: No value at JSON path "$.id", exception: Expected to find an object with property ['id'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
    at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:258)
    at ...
Run Code Online (Sandbox Code Playgroud)

Mik*_*ike 11

我发布后的5分钟就找到了答案.需要深入到阵列中.这有效:

.andExpect(jsonPath("$.[0].id",is(1)));
Run Code Online (Sandbox Code Playgroud)


jch*_*brt 5

您的JsonPath表达式是错误的,因为您体内的响应是一个数组。根据JsonPath Specification,此语法都是正确的:

"$[0][id]"
"$.[0].[id]"
"$[0].id"
"$.0.id"
Run Code Online (Sandbox Code Playgroud)

这个有用的页面还可以帮助您找出测试的jsonpath表达式。