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

163
Visualizações
Can not attach body to my POST request using Spring MockMvc

I'm trying to test my rest controller. No issues with GETs, but when I try to test a POST method I'm unable to attach the body.

private static final MediaType contentType = new MediaType(MediaType.APPLICATION_JSON.getType(),
                                                            MediaType.APPLICATION_JSON.getSubtype(),
                                                            Charset.forName("utf8"));
private ObjectMapper jsonMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);

@Test
public void test1() throws Exception {
    //...Create DTO
    //...Create same pojo but as entity

    when(serviceMock.addEntity(e)).thenReturn(e);

    mvc.perform(post("/uri")
        .contentType(contentType)
        .content(jsonMapper.writeValueAsString(dto))
        )
        .andDo(print())
        .andExpect(status().isCreated())
        .andExpect(content().contentType(contentType)); //fails because there is no content returned
}

This is the request output:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /uri
       Parameters = {}
          Headers = {Content-Type=[application/json;charset=UTF-8]}

There is no body. Why? I have printed jsonMapper.writeValueAsString(dto) and is not null.

edit:

Adding controller code:

@RestController
@RequestMapping("/companies")
public class CompanyController {

    @Autowired
    private CompanyService service;
    @Autowired
    private CompanyMapper mapper;



    @RequestMapping(method=RequestMethod.GET)
    public List<CompanyDTO> getCompanies() {
        List<Company> result = service.getCompanies();
        return mapper.toDtoL(result);
    }   

    @RequestMapping(method=RequestMethod.POST)
    @ResponseStatus(HttpStatus.CREATED)
    public CompanyDTO createCompany(@RequestBody @Valid CompanyDTO input) {
        Company inputE = mapper.toEntity(input);
        Company result = service.addCompany(inputE);
        return mapper.toDto(result);
    }
about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Solved.

  1. The mock call should use any instead of a concrete object: when(serviceMock.addCompany(any(Company.class))).thenReturn(e);

  2. I needed to override the equals method of the entity class to pass this statement: verify(serviceMock, times(1)).addCompany(e);

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