gpt4 book ai didi

java - Hibernate 监听器未在 Spring JUnit 测试中被调用

转载 作者:行者123 更新时间:2023-11-30 07:04:45 25 4
gpt4 key购买 nike

我正在创建使用 Hibernate 作为数据访问层的 Spring MVC 应用程序。我的所有实体都包含 createdOnupdatedOn 字段,其中包含创建/更新实体时的时间戳。 createdOn 字段使用 PreInsertEventListener 设置,updatedOn 字段使用 PreUpdateEventListener 设置。

当我运行我的应用程序时,它按预期工作,监听器被注册,当我保存一个实体时,适当的监听器被调用(使用调试器验证)。但是当我尝试对这种行为进行单元测试时,监听器已注册,但从未被调用。

我使用调试确定,当我在我的应用程序中保存一个实体时 EntityInsertAction#preInsert 被调用,它循环遍历已注册的监听器并调用它们。但是当我运行我的单元测试时,这个方法永远不会被调用。

这是我的单元测试示例:

@ActiveProfiles("test")
@Transactional
@TransactionConfiguration
@ContextConfiguration(classes = {
BaseConfiguration.class,
DatabaseConfiguration.class
})
@RunWith(SpringJUnit4ClassRunner.class)
public class HibernateListenerTest {

@Autowired
private FooDao fooDao;

@Test
public void testPreUpdateListener() {
Foo foo = fooDao.merge(createFoo());
Assert.assertNotNull(foo.getCreatedOn());
Assert.assertNull(foo.getUpdatedOn());

foo.setBar("Bar");
foo = fooDao.merge(foo);
Assert.assertNotNull(foo.getUpdatedOn());
}

}

因为没有调用监听器,单元测试总是失败并出现以下异常:

org.hibernate.PropertyValueException:非空属性引用空值或 transient 值

所以我的问题是:为什么运行应用程序和运行单元测试之间的这种行为不同,是否有办法修复代码以便在我的单元测试中正确调用监听器?

提前感谢您的任何意见。如果需要其他代码/信息,请发表评论。

最佳答案

如果您正在测试 Hibernate 监听器,只需调用 Session#flush在你的断言之前手动。

只需让 Spring 将 SessionFactory 注入(inject)到您的测试中并执行 sessionFactory.getCurrentSession().flush();

如果您希望您的监听器在刷新 session 之前采取行动,那么您需要使用不同的事件(例如 MERGE 或 PERSIST)。

关于java - Hibernate 监听器未在 Spring JUnit 测试中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27344122/

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