我正在尝试使用Spring Boot进行集成测试,但是发布请求不起作用。永远不会调用方法saveClientePessoaFisica,并且不会返回任何错误!我只是尝试使用get方法进行其他测试,并且它可以正常工作。
@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);
}
}
最佳答案
您的内容“teste”不是有效的JSON。当我使用您的代码时,我收到一个JsonParseException提示(顺便说一句,在content(“teste”)之后缺少括号)。同样有用的是使用andDo(print()),它将为您提供更详细的请求和响应:
@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());
}