如何使用Spring-Boot在JUnit集成测试中将mysql数据库更改为h2?

时间:2017-12-11 15:09:11

标签: java spring spring-boot junit spring-boot-test

我正在为整个应用程序编写@SpringBootTest集成测试。我只想通过嵌入式MYSQL测试数据库交换我的多数据源配置(H2)。应该正常加载所有其他应用程序类。

问题:我默认使用DataSourceBuilder将db初始化为apache tomcat数据库池。

在测试期间,虽然将spring.datasource.*属性更改为h2,但我仍然获得mysql连接。但为什么呢?

@Configuration
public class MultiDatasourceConfig {
    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.multi1")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean emf(
                EntityManagerFactoryBuilder builder, DataSource ds, JpaProperties jpaProperties) {
        return builder
                .dataSource(ds)
                .persistenceUnit("multi1")
                .properties(jpaProperties.getHibernateProperties(ds))
                .build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.multi2")
    public DataSource multi2DataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public LocalContainerEntityManagerFactoryBean multi2Emf(
                EntityManagerFactoryBuilder builder, @Qualifier("multi2DataSource") DataSource ds, JpaProperties jpaProperties) {
        return builder
                .dataSource(ds)
                .persistenceUnit("multi2")
                .properties(jpaProperties.getHibernateProperties(ds))
                .build();
    }
}

application-test.properties:

spring.datasource.multi1.driver-class-name=org.h2.Driver
spring.datasource.multi1.url=jdbc:h2:mem:ypsilon;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.multi1.username=sa
spring.datasource.multi1.password=sa
//multi2 accordingly

测试用例:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.ANY, connection = EmbeddedDatabaseConnection.H2)
@TestPropertySource(locations="classpath:application-test.properties")
public class MyTest {
}

结果:

  

org.springframework.beans.factory.BeanCreationException:错误   在类路径资源中定义名为'multi2'的bean   []:调用init方法失败;嵌套异常是   javax.persistence.PersistenceException:[PersistenceUnit:multi2]   无法构建Hibernate SessionFactory

     

引起:javax.persistence.PersistenceException:[PersistenceUnit:   multi2]无法构建Hibernate SessionFactory

行家:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>test</scope>
</dependency>

这很奇怪,因为在emf()内部调试期间,我可以看到DataSource ds已正确初始化。意味着它是一个H2 db,具有正确的URL等,就像我配置的那样。

更新:发现在生产中我正在运行:

spring.jpa.hibernate.ddl-auto=update

但如果表不存在,这也会创建表。

奇怪的是,在junit测试中,我必须按如下方式更改属性:

spring.jpa.hibernate.ddl-auto=create-drop

0 个答案:

没有答案