user2813807
user2813807

Reputation: 309

Deleted entity instance still exists in Spring boot unit test

In the jhipster sample spring boot application (https://github.com/jhipster/jhipster-sample-app), delete test are like that:

@Test
@Transactional
public void deleteBankAccount() throws Exception {
    // Initialize the database
    bankAccountRepository.saveAndFlush(bankAccount);
    int databaseSizeBeforeDelete = bankAccountRepository.findAll().size();

    // Get the bankAccount
    restBankAccountMockMvc.perform(delete("/api/bank-accounts/{id}", bankAccount.getId())
        .accept(TestUtil.APPLICATION_JSON_UTF8))
        .andExpect(status().isOk());

    // Validate the database is empty
    List<BankAccount> bankAccountList = bankAccountRepository.findAll();
    assertThat(bankAccountList).hasSize(databaseSizeBeforeDelete - 1);
}

I would like to make some further validation by doing a new get and checking a 404 error. But I have strange results (probably due to a transaction effect). After a delete on item #1, if I do this in my test:

 bankAccountRepository.findAll() // item 1 is not present => OK

 bankAccountRepository.findOne(1) // item 1 is present => BAD

 restBankAccountMockMvc.perform(get("/api/bank-accounts/{id}", bankAccount.getId())) // HTTP code 200 => BAD

I don't understand why findAll returns a list without the deleted item but findOne return the deleted item.

How can I have this?

 bankAccountRepository.findOne(1) // null

 restBankAccountMockMvc.perform(get("/api/bank-accounts/{id}", bankAccount.getId())) // HTTP code 404

Note: I didn't start my app from a jhipster project, I just look a the generated code to have good ideas. So I started my project from an empty maven/spring-boot project.

Upvotes: 1

Views: 608

Answers (1)

duderoot
duderoot

Reputation: 987

You are using the wrong Id for your asserts, i.e. you are deleting bankAccount.getId() which is not 1 because in the setup of the test a BankAccount is created. You should use for search also the same id which you have used for deleting: bankAccount.getId().

Upvotes: 1

Related Questions