2016-03-03 48 views
0

我正在使用SpringJUnit4ClassRunner運行我的集成測試。我必須在Spring Boot REST Web服務中使用兩個數據源,因爲我想爲Liquibase和Application查詢使用不同的數據庫用戶。當我運行測試時,第二個數據源沒有被創建。無法運行第二個數據源的Spring JUnit測試

以下是我的測試代碼

@RunWith(SpringJUnit4ClassRunner.class) 
@SpringApplicationConfiguration(classes = Application.class) 
@WebAppConfiguration 
@IntegrationTest 
public class DomainServiceImplTest { 

    @Test 
    public void testCreateDomain() throws Exception { 
    } 
} 

以下是我的數據源實例

@Configuration 
@EnableTransactionManagement 
public class DatabaseConfiguration { 

    private final Logger log = LoggerFactory.getLogger(DatabaseConfiguration.class); 

    @Inject 
    private Environment env; 

    @Autowired(required = false) 
    private MetricRegistry metricRegistry; 

    @Bean(destroyMethod = "close") 
    @Primary 
    public DataSource dataSource(DataSourceProperties dataSourceProperties, NileRegistrarProperties nileRegistrarProperties) { 
     log.debug("Configuring Datasource"); 
     if (dataSourceProperties.getUrl() == null) { 
      log.error("Your database connection pool configuration is incorrect! The application" + 
        " cannot start. Please check your Spring profile, current profiles are: {}", 
       Arrays.toString(env.getActiveProfiles())); 

      throw new ApplicationContextException("Database connection pool is not configured correctly"); 
     } 
     HikariConfig config = new HikariConfig(); 
     config.setDriverClassName(dataSourceProperties.getDriverClassName()); 
     config.setJdbcUrl(dataSourceProperties.getUrl()); 
     if (dataSourceProperties.getUsername() != null) { 
      config.addDataSourceProperty("user", dataSourceProperties.getUsername()); 
     } else { 
      config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user 
     } 
     if (dataSourceProperties.getPassword() != null) { 
      config.addDataSourceProperty("password", dataSourceProperties.getPassword()); 
     } else { 
      config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password 
     } 

     //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration 
     if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) { 
      config.addDataSourceProperty("cachePrepStmts", nileRegistrarProperties.getDatasource().isCachePrepStmts()); 
      config.addDataSourceProperty("prepStmtCacheSize", nileRegistrarProperties.getDatasource().getPrepStmtCacheSize()); 
      config.addDataSourceProperty("prepStmtCacheSqlLimit", nileRegistrarProperties.getDatasource().getPrepStmtCacheSqlLimit()); 
     } 
     if (metricRegistry != null) { 
      config.setMetricRegistry(metricRegistry); 
     } 
     return new HikariDataSource(config); 
    } 

    @Bean(destroyMethod = "close") 
    public DataSource liquibaseDataSource(DataSourceProperties dataSourceProperties, LiquibaseProperties liquibaseProperties) { 
     log.debug("Configuring Liquibase Datasource"); 
     if (dataSourceProperties.getUrl() == null) { 
      log.error("Your database connection pool configuration is incorrect! The application" + 
        " cannot start. Please check your Spring profile, current profiles are: {}", 
       Arrays.toString(env.getActiveProfiles())); 

      throw new ApplicationContextException("Database connection pool is not configured correctly"); 
     } 
     HikariConfig config = new HikariConfig(); 
     config.setDriverClassName(dataSourceProperties.getDriverClassName()); 
     config.setJdbcUrl(dataSourceProperties.getUrl()); 
     // Close all connections after liquibase operation is complete. 
     config.setMinimumIdle(0); 
     if (dataSourceProperties.getUsername() != null) { 
      config.addDataSourceProperty("user", liquibaseProperties.getUser()); 
     } else { 
      config.addDataSourceProperty("user", ""); // HikariCP doesn't allow null user 
     } 
     if (dataSourceProperties.getPassword() != null) { 
      config.addDataSourceProperty("password", liquibaseProperties.getPassword()); 
     } else { 
      config.addDataSourceProperty("password", ""); // HikariCP doesn't allow null password 
     } 

     return new HikariDataSource(config); 
    } 

    @Bean 
    public SpringLiquibase liquibase(@Qualifier("liquibaseDataSource") DataSource dataSource, 
            LiquibaseProperties liquibaseProperties) { 

     // Use liquibase.integration.spring.SpringLiquibase if you don't want Liquibase to start asynchronously 
     SpringLiquibase liquibase = new AsyncSpringLiquibase(); 
     liquibase.setDataSource(dataSource); 
     liquibase.setChangeLog("classpath:config/liquibase/master.xml"); 
     liquibase.setContexts(liquibaseProperties.getContexts()); 
     liquibase.setDefaultSchema(liquibaseProperties.getDefaultSchema()); 
     liquibase.setDropFirst(liquibaseProperties.isDropFirst()); 
     liquibase.setShouldRun(liquibaseProperties.isEnabled()); 

     log.debug("Configuring Liquibase"); 

     return liquibase; 
    } 
} 

以下是錯誤消息。

Error creating bean with name 'dataSourceInitializer': Invocation of init method failed; 

當我使用單一數據源時,一切工作正常。

+0

我剛剛意識到數據源變成了h2 DB在測試期間,並且我的LiquibaseProperties文件未被初始化。 – TechCrunch

+0

爲什麼你不使用application.properties進行數據源配置? –

+0

@RahulSharma我只使用application.yml進行配置。你在談論使用測試用例嗎? – TechCrunch

回答

1

我正在一個類似的項目,我有兩個數據源。這是我做的, datasource.primary.url=jdbc:mysql://localhost:3306/databaseName datasource.primary.username=username datasource.primary.password=password

同樣,對於第二個數據源, datasource.secondary.url=jdbc:mysql://localhost:3306/databaseName datasource.secondary.username=username datasource.secondary.password=password

而且在配置類做的只是,

@Bean 
@Primary 
@ConfigurationProperties(prefix = "datasource.primary") 
public DataSource primaryDataSource() { 
    return DataSourceBuilder.create().build(); 
} 

@Bean(name = "secondaryDatasource") 
@ConfigurationProperties(prefix = "datasource.secondary") 
public DataSource secondaryDataSource() { 
    return DataSourceBuilder.create().build(); 
} 

無論我需要一個數據源,我只是自動裝配它想:

public void setJdbcTemplate(@Qualifier("secondaryDatasource") DataSource dataSource) { 
    this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); 
} 

注:數據源註釋@Primary將如果在自動裝配時不使用@Qualifier,則注入。

這個測試非常簡單。如果你想使用內存數據庫進行測試(最常見的技術),只需提供另一組屬性,內存數據庫的url,這可以由測試類使用

+0

我的確完全像這樣。但是,這將保持連接池打開,即使我只需要在應用程序啓動時使用liquibase連接。 – TechCrunch

+0

重要嗎?您正在使用它進行測試。一旦測試完成,它將自動關閉。 –