【问题标题】:Spring: How can I test same class against multiple datasources?Spring:如何针对多个数据源测试同一个类?
【发布时间】:2014-05-24 22:13:39
【问题描述】:

考虑这个例子

@Test
public TestMyProjectIntegration {

  @Rule
  public JpaRule jpaRule = new JpaRule(H2);

  @Test
  ...
}
  • 我想针对localhost 中的H2 数据库运行我的集成测试,
  • 我想在 staging // Jenkins 中针对 MySQL 数据库运行我的集成测试

我最初想用Spring Profilesspring.profiles.active=developmentspring.profiles.active=staging我可以控制,但是

由于我将JpaRule 硬编码为H2,所以当spring.profiles.active 更改时,我不知道如何将此属性更改为MySQL

问题
在测试期间,spring推荐的指向不同数据库的方法是什么?

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    您可以使用传递数据库详细信息(如 -Dtest.database=H2)的系统属性调用测试,并在从 jenkins 调用测试时更改值

    @Rule
    public JpaRule jpaRule = new JpaRule(System.getProperty("test.database"));
    

    【讨论】:

      【解决方案2】:

      你已经完成了一半......所以在每个配置文件中你需要相同的 bean id 说dataSource

      <beans profiles="dev">
          <bean id="dataSource" class="H2"/>
      </beans>
      
      <beans profiles="stage">
          <bean id="dataSource" class="MySQL"/>
      </beans>
      

      然后在你的JpaRule

      @Rule
      public JpaRule jpaRule = new JpaRule(dataSource);
      

      然后确保您在正确的环境中设置了正确的 spring.active.profile。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-08-27
        • 1970-01-01
        • 2018-12-10
        • 2022-07-22
        • 1970-01-01
        • 2015-01-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多