0

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

4

1 回答 1

1

像往常一样模拟 save 方法。

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

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

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

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

@PersistenceContext
protected EntityManager em;

@AfterEach
void clearDb() {
  em.createQuery("DELETE FROM MyJpaClass").executeUpdate();
}
于 2020-04-02T13:52:08.730 回答