我想为项目的持久层创建单元测试,以确保实体被懒惰地加载。我正在使用带有springource的hibernate。 什么是基本的单元测试,可以保证我可以创建一个断言来检查? 至少对我来说,这里面临的挑战是,在交易过程中,我无法判断这些实体是否被懒散地取出并按需加载或急切地获取。
由于
答案 0 :(得分:1)
如果你有一个分离的对象,当你尝试访问该属性时,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);
}