当 spring 中的 jpaRepository.save() 使用 BDDMockito 测试时什么也不做

Do nothing when jpaRepository.save() in spring tests with BDDMockito

我现在正在我的应用程序中应用测试,但我不希望它填充我的数据库,我已经研究了使用不同数据库的方法,但还没有找到一种简单的方法来做到这一点.但是我找到了 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 方法,但我不知道我能做什么,除非覆盖我存储库的所有保存。

像往常一样模拟保存方法。

when(colaboradorRepository.save()).thenReturn(something);

你不能 doNothing 非 void 方法,因为它必须 return 一些东西。您可以 return null、空对象或其他内容。这取决于您的代码做什么以及您需要测试做什么。

可能需要额外的配置,例如排除您的存储库配置 class,但这可能会导致其他问题。

或者,让它写入数据库。像这样的测试通常只是一个嵌入式数据库,所以我不确定允许写入有什么问题。如果持久化数据导致问题,只需在每次测试后清除数据库 运行,或者在持久化实体时更加明智,这样您的测试就不会相互干扰。您可以在 @After (JUnit 4) 或 @AfterEach (JUnit 5) 方法中清除数据库。

@PersistenceContext
protected EntityManager em;

@AfterEach
void clearDb() {
  em.createQuery("DELETE FROM MyJpaClass").executeUpdate();
}