首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

【已解决】UT测试时候,怎么能保证Hibernate延迟加载有效

2012-10-28 
【已解决】UT测试时候,如何能保证Hibernate延迟加载有效?在Web应用中,我们可以使用OpenSessionInViewFilter

【已解决】UT测试时候,如何能保证Hibernate延迟加载有效?

在Web应用中,我们可以使用OpenSessionInViewFilter来保证延迟加载的可行性。那么在做UT时呢?此时并不能有效支持延迟加载,在Assert.assert***方法中就会遇到

?

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

?

?

的异常;异常也很明了,就是在调用POJO的get***时发现该POJO已经脱离了Session。解决该问题的点就在于使得Session要在UT执行完之后再关闭就可以了。仿照OpenSessionInViewFilter,我们实现一个父类的TestCase,其主要功能就是在执行UT前打开Session,并绑定Session;执行UT后关闭Session,代码如下:

@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:applicationContext-test.xml" })public abstract class JavenTestCase{    @Autowired    private SessionFactory sessionFactory;        protected Session getSession(SessionFactory sessionFactory)            throws DataAccessResourceFailureException    {        Session session = SessionFactoryUtils.getSession(sessionFactory, true);        session.setFlushMode(FlushMode.MANUAL);        return session;    }        @Before    public void setUp() throws Exception    {        Session session = getSession(sessionFactory);        TransactionSynchronizationManager.bindResource(sessionFactory,                new SessionHolder(session));    }        @After    public void tearDown() throws Exception    {        SessionHolder sessionHolder = (SessionHolder) TransactionSynchronizationManager.unbindResource(sessionFactory);        SessionFactoryUtils.closeSession(sessionHolder.getSession());    }    }

?

注:该类需要设置为abstract,否则执行UT时,会报出该类没有可以执行的test方法。

?

?

热点排行