Note that there are some explanatory texts on larger screens.

plurals
  1. POLazyInitializationException while unit-testing Hibernate entity classes for use in Spring, using TestNG
    primarykey
    data
    text
    <p>In my Spring configuration, I've asked that the session should remain open in my views:</p> <pre><code> &lt;bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"&gt; &lt;property name="sessionFactory" ref="sessionFactory"/&gt; &lt;property name="flushMode" value="0" /&gt; &lt;/bean&gt; </code></pre> <p>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.</p> <p>My unit test typically looks like this:</p> <pre><code>@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&lt;SomeEntity&gt; entities = mockEntity.getSomeEntitySet(); Assert.assertTrue(entities.size() &gt; 0); // This generates a LazyInitializationException } } </code></pre> <p>I've tried changing the setUp() to this:</p> <pre><code>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); } </code></pre> <p>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?</p> <p>Cheers</p> <p>Nik</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload