Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Test MockMvc perform post - Not working

I'm trying to make a Integration test using the Spring Boot but the post request is not working. The method saveClientePessoaFisica is never called and do not return any kind of error! I just tried to make other tests using a get method and it works properly.

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("dev")
public class ClienteControllerIT {

    @Autowired
    private MockMvc mvc;


    @Test
    public void nao_deve_permitir_salvar_cliente_pf_com_nome_cpf_duplicado() throws Exception {

        this.mvc.perform(post("/api/cliente/pessoafisica/post")
                .contentType(MediaType.APPLICATION_JSON)
                .content("teste")
                .andExpect(status().is2xxSuccessful());
    }

}

@RestController
@RequestMapping(path = "/api/cliente")
public class ClienteController {

    @Autowired
    private PessoaFisicaService pessoaFisicaService;


    @PostMapping(path = "/pessoafisica/post", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> saveClientePessoaFisica(@RequestBody PessoaFisica pessoaFisica) throws Exception {

        this.pessoaFisicaService.save(pessoaFisica);

        return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

}
like image 202
Pablo Souza Avatar asked Apr 18 '17 14:04

Pablo Souza


People also ask

What does MockMvc perform do?

The MockMvc instance is used to perform GET request that expects a JSON response. We check the response for a 200 'OK' response code, a JSON content type and a JSON response body containing the requested account.

Is MockMvc a unit or integration test?

Technically speaking, tests using MockMvc are in the boundaries between unit and integration tests. They aren't unit tests because endpoints are tested in integration with a Mocked MVC container with mocked inputs and dependencies.


1 Answers

Your content "teste" is no valid JSON. When I am using your code, I'm getting a JsonParseException complaining about that (By the way, there is a parenthese missing after content("teste") ). Also helpful is using andDo(print()) which will give you the request and response in more detail:

@Test
public void nao_deve_permitir_salvar_cliente_pf_com_nome_cpf_duplicado() throws Exception {

    this.mvc.perform(post("/api/cliente/pessoafisica/post")
            .contentType(MediaType.APPLICATION_JSON)
            .content("teste"))
            .andDo(print())
            .andExpect(status().is2xxSuccessful());
}
like image 192
Ralf Stuckert Avatar answered Oct 21 '22 20:10

Ralf Stuckert