Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init database before tests JUnit5 and Spring

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.

like image 307
telebog Avatar asked Jan 22 '26 22:01

telebog


1 Answers

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()
    }
}
like image 51
telebog Avatar answered Jan 25 '26 22:01

telebog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!