Using Spring for integration tests I am able to populate a test DB running scripts like so...
@Test
@Sql({"/db/schema.sql", "/db/accountConfig.sql", "/db/functions/fnSomething.sql"})
public void verifySomething() {
...
}
However, I'd like to run all my .sql
files only once before any test runs. Is there a JUnit 4 way to do this? It seems like @Sql
only runs for methods with the @Test annotations.
I'm using Junit 4, Spring Boot, Java 15, Testcontainers.
Things I've tried...
- I've tried using
@BeforeClass
on a class my test classes extend but that seems to run after my tests. - Testcontainers does have a init script function but it only takes one file, not ideal.
- I've also tried
ScriptUtils.executeSqlScript
but for some reason, test containers do not like that.
Here is my sample code that works with @Sql
but does not work with ScriptUtils.executeSqlScript
.
@ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
public abstract class AbstractIntegrationTest {
@ClassRule
public static MSSQLServerContainer mssqlserver = new MSSQLServerContainer();
public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
Properties props = new Properties();
props.put("spring.datasource.driver-class-name", mssqlserver.getDriverClassName());
props.put("spring.datasource.url", mssqlserver.getJdbcUrl());
props.put("spring.datasource.username", mssqlserver.getUsername());
props.put("spring.datasource.password", mssqlserver.getPassword());
environment
.getPropertySources()
.addFirst(new PropertiesPropertySource("myTestDBProps", props));
configurableApplicationContext.setEnvironment(environment);
}
}
My test classes simply extend AbstractIntegrationTest
. But using @Sql
runs scripts for every test case. Does anyone have a suggestion for a better way to init SQL scripts? Tried flyway but it won't allow the creation of a DB from a script.