zonkyio / embedded-database-spring-test

A library for creating isolated embedded databases for Spring-powered integration tests.
Apache License 2.0
399 stars 37 forks source link

How to run schema creation SQL statements before context initialization? #275

Open soid opened 1 month ago

soid commented 1 month ago

I'm trying to use @Sql annotation for initializing the db schema like this: @Sql(scripts = ["/schema.sql"]) (the code is in Kotlin here)

But it seems it is only executed after spring context in initialized. So, if my components rely on loading the db in initialization then it fails. For example, if I want to use the db in @PostConstruct method of my component:

@Component
class MyService(val personRepository: PersonRepository) {
    @PostConstruct
    fun init() {
        val persons = personRepository.findAll()
        println("Counted persons: " + persons.count())
    }
    ...

then it fails during Spring context initialization due to missing table. This is because schema.sql is only executed after the initialization.

I also tried to no avail:

tomix26 commented 1 month ago

Hey @soid, thanks for the question. The easiest way is to use a database migration tool like Flyway or Liquibase. Then you can be sure that the production and test schemas are the same. Alternatively, you can use a DataSourceInitializer bean for this purpose: https://stackoverflow.com/questions/23029722/how-to-execute-sql-insert-queries-to-populate-database-during-application-start