我想为我的项目的持久层创建单元测试,以确保实体被延迟加载。我正在使用 hibernate 和 springsource。 什么是可以保证我可以创建断言来检查的基本单元测试? 至少对我来说,这里的挑战是,在事务中,我无法判断实体是延迟获取并按需加载还是急切获取。
谢谢
最佳答案
如果你有一个分离的对象,当你尝试访问该属性时,hibernate将抛出一个LazyInitializationException。
@Test(expected=LazyInitializationException.class)
public void lazyLoadTest() {
//get a session object
Session session = dao.getSession();
//load object
Foo foo = dao.findById(1);
//if you have a detached object, this would be unnessary
session.close();
//if lazy loading is working, an exception will be thrown
//note: If you don't try to access the collection (.size(), the data will not be fetched)
foo.getBars().size();
}
您还可以使用 Hibernate.isInitialized
@Test
public void anotherLazyLoadTest() {
//get a session object
Session session = dao.getSession();
//load object
Foo foo = dao.findById(1);
//if you have a detached object, this would be unnessary
session.close();
boolean isInitialized = Hibernate.isInitialized(foo.getBars());
assertFalse(isInitialized);
}
关于java - 如何在 Java 中创建一个单元测试来确保我的 JPA 数据库实体被延迟加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20647016/