【问题标题】:Deleted entity instance still exists in Spring boot unit testSpring boot单元测试中仍然存在已删除的实体实例
【发布时间】:2017-11-02 08:48:59
【问题描述】:

在jhipster sample spring boot application (https://github.com/jhipster/jhipster-sample-app)中,删除测试是这样的:

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

我想通过执行新的获取并检查 404 错误来进一步验证。但我有奇怪的结果(可能是由于交易效应)。 删除项目 #1 后,如果我在测试中这样做:

 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

我不明白为什么 findAll 返回一个没有已删除项目的列表,而 findOne 返回已删除项目。

我怎样才能拥有这个?

 bankAccountRepository.findOne(1) // null

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

注意:我不是从 jhipster 项目开始我的应用程序,我只是查看生成的代码以获得好的想法。所以我从一个空的 maven/spring-boot 项目开始我的项目。

【问题讨论】:

    标签: java rest spring-boot spring-data-jpa jhipster


    【解决方案1】:

    您在断言中使用了错误的 ID,即您正在删除不是 1 的 bankAccount.getId(),因为在测试设置中创建了 BankAccount。您还应该使用与删除相同的 id 进行搜索:bankAccount.getId()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-25
      • 2017-01-17
      • 1970-01-01
      • 2015-08-18
      • 2022-01-03
      • 2022-07-31
      • 2019-07-09
      • 2017-12-11
      相关资源
      最近更新 更多