No more ‘LazyInitializationException’ in your integration tests

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

@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(

protected static SessionFactory sessionFactory;

private AccountService accountService;

public static void oneTimeSetUp() throws Exception {
sessionFactory = (SessionFactory) ctx.getBean(SESSION_FACTORY);
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
new SessionHolder(session));

public static void oneTimeTearDown() throws Exception {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager

public void testCreateAccount() {

// Do you test here.





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)

    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: Logo

You are commenting using your 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