我现在正在我的应用程序中应用测试,但我不希望它填充我的数据库,我已经研究了使用不同数据库的方法,但还没有找到一种简单的方法来做到这一点。但是我发现了 BDDMockito,它可以帮助我控制调用 jpaRepository 时会发生什么。
我已经尝试将 BDDMockito 与 .doNothing 方法一起使用,但似乎无法与 jpaRepository.save() 一起使用,这是我的代码:
public void postColaborador(String sobreNome, String rg, String cpf, String orgaoExpedidor, String nomePai, String nomeMae,
LocalDate dataNascimento, String estadoCivil, String tipoCasamento, PessoaFisica conjuge,
String profissao, String matricula, String nome, String escopo, Endereco endereco, String secretaria,
String idCriador) throws JsonProcessingException {
Colaborador colaborador = new Colaborador(sobreNome, rg, cpf, orgaoExpedidor, nomePai, nomeMae, dataNascimento,
estadoCivil, tipoCasamento, conjuge, profissao, matricula);
colaborador.setNome(nome);
colaborador.setEscopo(escopo);
colaborador.setEndereco(endereco);
BDDMockito.doNothing().when(colaboradorRepository).save(colaborador); //this should make jpa do nothing when I call method save
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:" + port + "/api/colaborador/cadastrar")
.queryParam("colaborador", objectMapper.writeValueAsString(colaborador))
.queryParam("setor", secretaria)
.queryParam("idCriador", idCriador);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<String> response = testRestTemplate.exchange(
builder.build().encode().toUri(),
HttpMethod.POST,
entity,
String.class);
Assertions.assertEquals(HttpStatus.OK, response.getStatusCode());
}
当我执行测试时,我收到此错误:
org.mockito.exceptions.base.MockitoException: Only void methods can doNothing()! Example of correct use of doNothing():
doNothing().
doThrow(new RuntimeException())
.when(mock).someVoidMethod(); Above means: someVoidMethod() does nothing the 1st time but throws an exception the 2nd time is called
我看到 save 不是一个 void 方法,但我不知道我能做什么,除非覆盖我所有的存储库保存。