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

Davi Bogo :

I'm applying tests in my application right now, but I don't want it to populate my database, I've researched for ways to use a different database but haven't found a simple way to do it. But I found BDDMockito, that helps me to control what will happen when I call my jpaRepository.

I've tried using BDDMockito with the method .doNothing, but it seems impossible to use with jpaRepository.save(), this is my code:

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());
}

When I execute the test I get this error:

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

I see that save is not a void method, but I don't know what I can do unless ovewrite all my saves of my repositories.

Christopher Schneider :

Just mock the save method as you normally would.

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

You can't doNothing on a non-void method, because it has to return something. You can return null, an empty object, or something else. It depends on what your code does and what you need your test to do.

There may be additional configuration required, such as excluding your repository configuration class, but that may cause other problems.

Alternatively, just let it write to the database. Tests like this are usually just an embedded database, so I'm not sure what's wrong with allowing a write. If persisted data is causing problems, just clear the database after each test run, or be more sensible when persisting your entities so your tests don't step on each other. You can clear the database in your @After (JUnit 4) or @AfterEach (JUnit 5) methods.

@PersistenceContext
protected EntityManager em;

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=388932&siteId=1