简体   繁体   English

Spring Boot集成测试

[英]Spring boot Integration Test

I'm currently using spring boot for my application development. 我目前正在使用Spring Boot进行应用程序开发。 In this case it auto configures most of the beans including the data source. 在这种情况下,它将自动配置大多数Bean,包括数据源。 However I had a need to customize the Datasource configuration and hence created a new DatabaseConfig as follows. 但是,我需要自定义数据源配置,因此按如下所示创建了一个新的DatabaseConfig。

@Configuration
public class DatabaseConfig {

  @Bean
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(...);
        dataSourceBuilder.username(...);
        dataSourceBuilder.password(...);
        dataSourceBuilder.driverClassName(...);
        return dataSourceBuilder.build();

    }
}

This works fine. 这很好。

Now I have a spring mvc Integration test which tests the rest endpoints. 现在,我有一个Spring MVC Integration测试,可以测试其余的端点。 I have a need to ignore the above Database config while running the tests so that spring boot auto configures an embedded datasource(HSQL db is on the class path) 我需要在运行测试时忽略上述数据库配置,以便Spring Boot自动配置嵌入式数据源(类路径上的HSQL db)

How can I accomplish the same ? 我该怎么做?

You can create a second dataBase and set profile for each database. 您可以创建另一个数据库并为每个数据库设置配置文件。 While running your tests you need only to write @ActiveProfile("nameOfProfile") above your Test class. 运行测试时,您只需要在Test类上方编写@ActiveProfile("nameOfProfile") For example: 例如:

@Bean
@Profile("One")
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(...);
        dataSourceBuilder.username(...);
        dataSourceBuilder.password(...);
        dataSourceBuilder.driverClassName(...);
        return dataSourceBuilder.build();
@Bean
@Profile("Two")
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(...);
        dataSourceBuilder.username(...);
        dataSourceBuilder.password(...);
        dataSourceBuilder.driverClassName(...);
        return dataSourceBuilder.build();

@SpringBootTest
@ActiveProfile("Two")
public class Test{
}

You can create database configuration for tests and annotate test bean as primary: 您可以为测试创建数据库配置,然后将测试bean注释为主数据库:

@Configuration
public class TestDatabaseConfig {

    @Bean
    @Primary
    public DataSource dataSource() {
        DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
        dataSourceBuilder.url(...);
        dataSourceBuilder.username(...);
        dataSourceBuilder.password(...);
        dataSourceBuilder.driverClassName(...);
        return dataSourceBuilder.build();

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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