En mi controlador Spring tengo un método que devuelve el siguiente json:
[ { "id": 2, "dto": null, "user": { "userId": 2, "firstName": "Some", "lastName": "Name", "age": 100, "aboutMe": "boring" }, "isYoung": false, "isOk": false } ]Estoy tratando de escribir una prueba para este getter. Aquí está mi prueba:
@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))); }Aparentemente no estoy entendiendo esto bien:
Aunque si ejecuto la prueba solo para $[0].id, la prueba pasa. Sin embargo, para todos los demás casos (para el objeto de usuario anidado y los campos isYoung e isOk) obtengo un error de excepción de índice de matriz.
¿Alguna idea? ¡Gracias!
Si la prueba es:
@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("$[0].user.userId", is(2))) .andExpect(jsonPath("$[0].user.firstName", is("Some"))) .andExpect(jsonPath("$[0].user.lastName", is("Name"))) .andExpect(jsonPath("$[0].isYoung", is(false))) .andExpect(jsonPath("$[0].isOk", is(false))); }