【发布时间】:2009-10-09 12:37:55
【问题描述】:
在我的 Spring 配置中,我要求会话在我的视图中保持打开状态:
<bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="flushMode" value="0" />
</bean>
但是,这个 bean 显然没有将我的 TestNG 单元测试视为视图。 ;-) 没关系,但是是否有用于单元测试的类似 bean,以便我在单元测试时避免可怕的 LazyInitializationException?到目前为止,我有一半的单元测试因此而死。
我的单元测试通常如下所示:
@ContextConfiguration({"/applicationContext.xml", "/applicationContext-test.xml"})
public class EntityUnitTest extends AbstractTransactionalTestNGSpringContextTests {
@BeforeClass
protected void setUp() throws Exception {
mockEntity = myEntityService.read(1);
}
/* tests */
@Test
public void LazyOneToManySet() {
Set<SomeEntity> entities = mockEntity.getSomeEntitySet();
Assert.assertTrue(entities.size() > 0); // This generates a LazyInitializationException
}
}
我已尝试将 setUp() 更改为:
private SessionFactory sessionFactory = null;
@BeforeClass
protected void setUp() throws Exception {
sessionFactory = (SessionFactory) this.applicationContext.getBean("sessionFactory");
Session s = sessionFactory.openSession();
TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));
mockEntity = myEntityService.read(1);
}
但我认为这是错误的处理方式,我将交易搞砸以备后续测试。有没有像 OpenSessionInTestInterceptor 这样的东西,有没有更好的方法来做到这一点,或者这是这样做的方法,在这种情况下我误解了什么?
干杯
尼克
【问题讨论】:
标签: java unit-testing hibernate spring testng