Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

276
Visualizações
Unit Test Spring MVC Rest Service: array jsonPath

In my Spring controller I have a method that returns the following json:

[
  {
    "id": 2,
    "dto": null,
    "user": {
      "userId": 2,
      "firstName": "Some",
      "lastName": "Name",
      "age": 100,
      "aboutMe": "boring"
    },
    "isYoung": false,
    "isOk": false
  }
]

I'm trying to write a test for this getter.Here is my test:

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

Apparently I'm not getting this right:

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.

Any ideas?Thanks!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Should the test be:

@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)));
}
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda