gpt4 book ai didi

java - JUnit 测试仅在调用 Assert 后捕获异常

转载 作者:太空宇宙 更新时间:2023-11-04 06:52:54 25 4
gpt4 key购买 nike

方法countryDao.delete(countryEntity)应该抛出ConstraintViolationException,并且只有抛出异常时测试才应该通过。

但是,下面表单中的测试未通过,我收到消息“java.lang.AssertionError:预期测试会抛出 org.hibernate.exception.ConstraintViolationException 的实例”

@Test
public void testDeleteWithCities() throws Exception {
exception.expect(ConstraintViolationException.class);
CountryEntity countryEntity = countryDao.find(1L);
countryDao.delete(countryEntity);
}

将最后一行添加到测试后,它确实通过了:

@Test
public void testDeleteWithCities() throws Exception {
exception.expect(ConstraintViolationException.class);
CountryEntity countryEntity = countryDao.find(1L);
countryDao.delete(countryEntity);
Assert.assertEquals(3, countryDao.findAll().size());
}

它应该像这样吗?我相信不需要 Assert.assertEquals(3,countryDao.findAll().size());

感谢您的帮助。

最佳答案

我的猜测是您的测试是事务性的。因此,DAO.delete() 方法是在用于测试方法的事务中完成的。

delete()remove() 不会立即删除实体,就像 persist() 不会立即插入实体一样。它只是将实体标记为已删除,并且在下一次刷新时,Hibernate 将执行删除查询。

当调用 findAll() 时,您会隐式刷新 Hibernate session (以确保 findAll() 不会返回之前删除的实体)。因此此时执行删除查询,这会导致 ConstraintViolationException

您可以通过打开 SQL 日志记录、逐行执行代码并检查每一步生成的 SQL 查询来确认这一点。

因此,要么不要让您的测试具有事务性,要么在测试中显式调用 flush()(这使得意图比调用 findAll() 更清晰)。

关于java - JUnit 测试仅在调用 Assert 后捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23119626/

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