【问题标题】:Set Spring Unit Test Profile From -D Variables从 -D 变量设置 Spring 单元测试配置文件
【发布时间】:2015-11-06 15:30:16
【问题描述】:

我有这样的测试

RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { AppConfig.class, DevConfig.class, ProdConfig.class})
@ActiveProfiles({"prod", "dev"})
public class MyTest {
 ........
}

AppConfig 是我的应用程序的主要配置

我的单元测试创​​建了两个配置类 DEV 配置类从我的 src/test/resource/... 加载 test_dev.properties。

@Configuration
@Profile("dev")
@PropertySource("classpath:test_dev.properties")
public class DevConfig {

}

ProdConfig 类加载 prod.properties

@Configuration
@Profile("prod")
@PropertySource("classpath:test_prod.properties")
public class ProdConfig {

}

我想通过更改 @ActiveProfiles 中的值在 prod 和 dev 之间轻松切换

但我希望能够像这样切换测试环境

 mvn -Dspring.profiles.active=dev or prod  install 

我试过了

   @ActiveProfiles({"prod", "dev"})
   then 
   mvn -Dspring.profiles.active=dev or prod  install 

似乎总能捡到刺

我见过类似的解决方案

@Test
    public void transferTenDollars() throws InsufficientFundsException {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        ctx.getEnvironment().setActiveProfiles("dev");
        ctx.register(TransferServiceConfig.class, StandaloneDataConfig.class, JndiDataConfig.class);
        ctx.refresh();

        // proceed with assertions as above ...
    }

但这会失去使用@ContextConfiguration 注解的全部意义。

【问题讨论】:

    标签: java spring


    【解决方案1】:

    我认为开关是

    -Dspring.profiles.active=dev
    

    甚至作为环境变量

    SPRING_PROFILES_ACTIVE=dev mvn install
    

    【讨论】:

    • 你是对的。但删除 @ActiveProfiles({"prod"}) 是解决我的问题的关键
    • reason remove @ActiveProfiles({"prod", "dev"}) 解决了这个问题,因为您不想从代码中指定活动配置文件,而是想从命令行环境变量传递它。因此不需要做@ActiveProfiles
    • 您可以同时使用带有固定配置文件的注释 @ActiveProfiles({"foo"}) 并从命令行添加更多内容 -Dspring.profiles.include=bar,baz
    猜你喜欢
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-01
    • 2018-08-01
    相关资源
    最近更新 更多