Reputation: 13481
How can I get Spring Boot to recreate in-memory test databases from scratch between test classes?
I've got several local integration tests annotated with @SpringApplicationConfiguration
and @WebIntegrationTest
that alter database state. I have marked each of these with @DirtiesContext
. I was expecting the code to create the in-memory database would be part of the ApplicationContext
lifecycle, and so a new one should get created in any subsequent tests.
I can see in the logs that Flyway is trying to re-apply migrations and thinks they're already done as the database hasn't been purged.
Is Spring Boot creating the in-memory database outside of each ApplicationContext
and sharing it between them? Is there any way to control this behaviour?
EDIT
I'm also seeing odd behaviour when running tests from Maven as opposed to Eclipse. One of my database tables is changing state in Maven, but not in Eclipse. Could this be a ClassLoader issue?
Upvotes: 4
Views: 1512
Reputation: 31197
Without being able to inspect the configuration and run-time behavior of your project, I can only assume that you are running into the same problem described in SPR-8849.
Is Spring Boot creating the in-memory database outside of each
ApplicationContext
and sharing it between them?
That's unlikely. What's more likely is that the database is created only once when the first ApplicationContext
is loaded, and that one single database is used across all tests executing within in the same JVM. This would explain the fact that "the database hasn't been purged," as you phrased it.
Is there any way to control this behaviour?
If my above assumptions are correct, yes: you can control this by making sure that you use a unique database name for each embedded database. See the comments in SPR-8849 for details.
Please let me know if that works for you.
Regards,
Sam (author of the Spring TestContext Framework)
Upvotes: 4
Reputation: 13481
Specifying custom configuration yields the expected behaviour.
@Configuration
@EnableAutoConfiguration(exclude={
SecurityAutoConfiguration.class,
ManagementSecurityAutoConfiguration.class,
DataSourceAutoConfiguration.class
})
@EnableJpaRepositories(basePackages = "com.example.repository")
public class TestConfig {
@Bean
public String sharedSecret() {
return null;
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.HSQL)
.build();
}
}
If anyone from Pivotal reads this (does Dave Syer have a big red phone?), I can knock up a test project to exhibit the behaviour if you think it's a bug.
Upvotes: 2