简体   繁体   中英

Spring Boot different data.sql files for different h2 tests

@RunWith(SpringRunner.class)
@SpringBootTest(classes=Application.class)
public class TaskProviderTest {
}

I'm using h2 database configured in property file

spring.datasource.url=jdbc:h2:mem:testdb;MODE=PostgreSQL
spring.datasource.platform=h2
spring.jpa.hibernate.ddl-auto=none
spring.datasource.continue-on-error=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop

And I'm using schema.sql and data.sql files for unit tests. Both scripts are executed on test startup.

Is there anyway to use different data.sql files for different Junit test cases ?

Try to use EmbeddedDataSource and configure it from method in code. The code below is demonstrates how to create datasource with 2 sql scripts

@Bean
public DataSource dataSource() {
    final EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();

    return builder
            .setType(EmbeddedDatabaseType.HSQL)
            .addScript("sql/create-db.sql")
            .addScript("sql/fill-db.sql")
            .build();
}

You can use Spring's EmbeddedDatabaseBuilder to construct the database in the setUp() method of your unit tests, providing different data.sql scripts for different tests.

Example:

public EmbeddedDatabase database(String dataScript) {
    return new EmbeddedDatabaseBuilder().
            setType(H2).
            addScript("schema.sql").
            addScript(dataScript).
            build();
}

Reference:

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/datasource/embedded/EmbeddedDatabaseBuilder.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM