My project is using Spring, Hibernate ant JUnit 5. What is the best approach to init DB before all test?
Here is how I tired to do it:
class DbCreatorService {
@Autowired
private Service1;
@Autowired
private Service2;
....
}
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
@Transactional
class MyTest {
@BeforeAll
static void initDatabase(@Autowired DbCreatorService dbCreatorService ) {
dbCreatorService.initDB()
}
}
When I call sessionFactory.getCurrentSession() somewhere in the initDB() I get: org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread. sessionFactory is injected with @Autowired.
My tests just read from the DB and I wanted to init DB only once before all tests. My final solution:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
@Transactional
class MyTest {
@Autowired
private DbCreatorService dbCreatorService;
@BeforeAll
void initDatabase() {
dbCreatorService.initDB()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With