9

I am having an issue with testing and json path

I am just trying to perform a simple test and check the value of 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)));

But I get an error like the following. Seems like my code should be checking the id value. Am I not being specific enough since there are multiple items in the returned JSON? Any help is appreciated. Thanks.

     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 ...
Mike
  • 763
  • 2
  • 12
  • 25
  • Also you can always open any JSON path evaluator online tool, insert your JSON and test directly how the field is retrieved with your jsonPath query. – LexSav Jul 20 '22 at 06:59

2 Answers2

12

I figured out the answer5 minutes after posting. Needed to go deeper into the array. This works:

.andExpect(jsonPath("$.[0].id",is(1)));
Mike Partridge
  • 5,128
  • 8
  • 35
  • 47
Mike
  • 763
  • 2
  • 12
  • 25
  • It didnt work for me https://stackoverflow.com/questions/47818094/json-keys-having-space – paul Dec 15 '17 at 12:19
8

Your JsonPath expression is wrong, because your response in the body is an array. According to the JsonPath Specification, this syntaxes are all correct:

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

This useful page can also help you to find out the jsonpath expression for your tests.

jchrbrt
  • 1,006
  • 1
  • 11
  • 12
  • It didnt work for me https://stackoverflow.com/questions/47818094/json-keys-having-space – paul Dec 15 '17 at 12:19