LazyInitializationException when unit testing Hibernate entity classes for use in Spring using TestNG

In my Spring configuration, I asked for the session to 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 does not conscientiously treat my TestNG test cases as a representation. ;-) Everything is fine, but are there any similar bean for unit tests so that I avoid the terrible LazyInitializationException when unit testing? So far, half of my unit tests are dying because of this.

My unit test usually 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 tried changing 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);
}

, , . - OpenSessionInTestInterceptor, , , , ?

+1
2

.. , , setUp().

, , , , , . , :

  • setUp()
  • .
  • ( ) tearDown()

(1), (2) (3) - , LazyInitializationException. mockEntity = myEntityService.read(1); setUp (), ; setUp, , .

+1

JUnit , TestNG. Personnaly SpringJUnit4ClassRunner :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext-struts.xml")
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public abstract class BaseTests {

"@Before" MockHttpServletRequest RequestContextHolder:

@Before
public void prepareTestInstance() throws Exception {
    applicationContext.getBeanFactory().registerScope("session", new SessionScope());
    applicationContext.getBeanFactory().registerScope("request", new RequestScope());
    MockHttpServletRequest request = new MockHttpServletRequest();

    ServletRequestAttributes attributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(attributes);

     .......

+6

Source: https://habr.com/ru/post/1731449/


All Articles