Make Spring Boot Recreate Test Databases

大憨熊 提交于 2019-12-10 15:54:41

问题


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?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/28694536/make-spring-boot-recreate-test-databases

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!