No more ‘LazyInitializationException’ in your integration tests

Below an example of what you need to do using JUnit 4 to prevent ‘LazyInitializationException’.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { “classpath:application-context-test.xml” })
public class AccountServiceIntregrationTests extends
AbstractTransactionalJUnit4SpringContextTests {

protected static final String SESSION_FACTORY = “sessionFactory”;

protected static ApplicationContext ctx =
new ClassPathXmlApplicationContext(
“classpath:application-context-test.xml”);

protected static SessionFactory sessionFactory;

@Autowired
private AccountService accountService;

@BeforeClass
public static void oneTimeSetUp() throws Exception {
sessionFactory = (SessionFactory) ctx.getBean(SESSION_FACTORY);
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
session.setFlushMode(FlushMode.MANUAL);
TransactionSynchronizationManager.bindResource(sessionFactory,
new SessionHolder(session));
}

@AfterClass
public static void oneTimeTearDown() throws Exception {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager
.unbindResource(sessionFactory);
SessionFactoryUtils.closeSession(sessionHolder.getSession());
}

@Test
public void testCreateAccount() {

// Do you test here.

}

}

Cheers,

Ana

Advertisements

2 thoughts on “No more ‘LazyInitializationException’ in your integration tests

  1. Apparently adding the following annotation to the class also works and the configuration I explained above is not needed anymore.

    @TransactionConfiguration(transactionManager = “transactionManager”, defaultRollback = true)
    @Transactional

    However, the @Rollback(true) is not working for me, since I get DataIntegrityViolationException.

    😦

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s