Spring testing and JsonPath issue

I have a problem with testing and json path

I am just trying to run a simple test and check the id value:

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)));

But I get an error as shown below. It looks like my code should check the id value. I'm not specific enough, since there are several elements in the returned JSON? Any help is appreciated. Thank.

     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 ...
+4
source share
2 answers

I found out the answer 5 minutes after posting. You need to go deeper into the array. It works:

.andExpect(jsonPath("$.[0].id",is(1)));
+7
source

Your JsonPath expression is incorrect because your answer in the body is an array. According to the JsonPath Specification , these syntaxes are correct:

"$[0][id]"
"$.[0].[id]"
"$[0].id"
"$.0.id"

jsonpath .

+2

Source: https://habr.com/ru/post/1659045/


All Articles