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
Thanks to Salomo that helped me with JUnit 4!
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.
😦