我正在尝试使用Spring Boot进行集成测试,但是post请求不起作用 . 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);
}
}
2 回答
您的内容“teste”不是有效的JSON . 当我使用你的代码时,我得到一个JsonParseException抱怨(顺便说一下,在内容(“teste”)之后有一个括号丢失) . 使用andDo(print())也很有帮助,它会更详细地为您提供请求和响应:
有些事要寻找:
在mockmvc中启用日志记录
正确启用mockmvc
使用spring security时,请在mockmvc中初始化它
使用spring security / CSRF / HTTP POST时,在mockmvc中传递csrf
启用调试日志记录
像这样 :
工作测试: