title: Unit Test Spring MVC Rest Service: array jsonPath
body: <p>In my Spring controller I have a method that returns the following json:</p>
  
  <pre><code>[
    {
      "id": 2,
      "dto": null,
      "user": {
        "userId": 2,
        "firstName": "Some",
        "lastName": "Name",
        "age": 100,
        "aboutMe": "boring"
      },
      "isYoung": false,
      "isOk": false
    }
  ]
  </code></pre>
  
  <p>I'm trying to write a test for this getter.Here is my test:</p>
  
  <pre><code>@Test
  public void getterMethod() throws Exception{
      mockMvc.perform(get("/path?id=1")).andExpect(status().isOk())
          .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
          .andExpect(jsonPath("$[0].id", is(2)))
          .andExpect(jsonPath("$[2].user.userId", is(2)))
          .andExpect(jsonPath("$[2].user.firstName", is("Giorgos")))
          .andExpect(jsonPath("$[2].user.lastName", is("Ant")))
          .andExpect(jsonPath("$[3].isYoung", is(false)))
          .andExpect(jsonPath("$[4].isOk", is(false)));
  }
  </code></pre>
  
  <p>Apparently I'm not getting this right:</p>
  
  <p>Although if I run the test only for the $[0].id the test passes. However for all the rest cases (for the nested user object and isYoung fiels and isOk) I'm getting an array index exception error.</p>
  
  <p>Any ideas?Thanks!</p>