Spring documentation warns about False Positives in Transactional
tests and suggest the following:
// ...
@Autowired
SessionFactory sessionFactory;
@Transactional
@Test // no expected exception!
public void falsePositive() {
updateEntityInHibernateSession();
// False positive: an exception will be thrown once the Hibernate
// Session is finally flushed (i.e., in production code)
}
@Transactional
@Test(expected = ...)
public void updateWithSessionFlush() {
updateEntityInHibernateSession();
// Manual flush is required to avoid false positive in test
sessionFactory.getCurrentSession().flush();
}
// ...
I have the following base class:
@SpringBootTest
@Transactional
@AutoConfigureMockMvc
public abstract class BaseSpringBootTest {
and a class that extends it where I want to apply this practice of injecting the sessionFactory
:
public class EmployeeRepositoryTest extends BaseSpringBootTest {
@Autowired
SessionFactory sessionFactory
but I am getting:
NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available
I also tried injecting
@Autowired
EntityManagerFactory entityManagerFactory;
and then calling:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
sessionFactory.getCurrentSession();
but this throws the following Exception:
org.hibernate.HibernateException: No CurrentSessionContext configured!
How do I get a reference to currentSession
in a test, so that I can finally call:
sessionFactory.getCurrentSession().flush();
as documented in Spring Boot documentation?