gpt4 book ai didi

java - 在 BDDMockito 的 Spring 测试中,当 jpaRepository.save() 时不执行任何操作

转载 作者:行者123 更新时间:2023-12-02 08:47:16 24 4
gpt4 key购买 nike

我现在正在我的应用程序中应用测试,但我不希望它填充我的数据库,我已经研究了使用不同数据库的方法,但还没有找到简单的方法。但我发现了 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);

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

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

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

@PersistenceContext
protected EntityManager em;

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

关于java - 在 BDDMockito 的 Spring 测试中,当 jpaRepository.save() 时不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60992854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com