0

我想为我的项目的持久层创建单元测试,以确保实体被延迟加载。我正在使用带有springsource的hibernate。什么是可以保证我可以创建断言来检查的基本单元测试?至少对我来说,这里的挑战是,在事务中,我无法判断实体是被懒惰地获取并按需加载还是急切地获取。

谢谢

4

1 回答 1

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);
}
于 2013-12-18T18:21:01.253 回答