Hi guys,
In my Spring configuration, I've asked that the session should remain open in my views:
<bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
<property name="sessionFactory" ref="sessionFactory"/>
<property name="flushMode" value="0" />
</bean>
However, this bean obiously doesn't consider my TestNG unit tests as a view. ;-) That's all right, but is there a similar bean for unit tests so that I avoid the dreaded LazyInitializationException while unit-testing? So far, half of my unit tests die because of it.
My unit test typically looks like this:
@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
}
}
I've tried changing the setUp() to this:
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);
}
but I believe this is the wrong way to go about it, and I mess the transaction up for later tests. Is there something like an OpenSessionInTestInterceptor, are there better ways of doing this, or is this the way to do it and in that case what have I misunderstood about it?
Cheers
Nik