Search code examples
javaspringspring-booth2spring-boot-test

How to add an init script to h2 junit spring test?


I have a @SpringBootTest that makes use of an inmemory h2 db for junit testing:

spring.datasource.cache.url=jdbc:h2:mem:;MODE=MYSQL
spring.datasource.cache.username=test
spring.datasource.cache.password=test

Question: how can I add an schema creation script to it on startup of the h2 db, but only for one or some tests?


Solution

  • Basically you can try using @Sql annotation on the test that would like to generate the schema/data/etc.

    Give it a script that will contain schema definition and you're good to go.

    @Sql("/generate_schema.sql")
    public class MyTest {
    }