2015-11-06 118 views
0

我有这样的设置弹簧单元测试配置文件从-D变量

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

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

有刚刚创建来回我的单元测试两个配置类 从我的src /测试/资源的DEV配置类负载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 { 

} 

我想在@Act​​iveProfiles

改变值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注解整点。

回答

1

我觉得开关

-Dspring.profiles.active=dev 

甚至可变

SPRING_PROFILES_ACTIVE=dev mvn install 
+0

你是正确的环境。但删除@ActiveProfiles({“prod”}) 是解决我的问题的关键 – user5324782

+0

原因删除@ActiveProfiles({“prod”,“dev”})解决了问题是因为,而不是从您的代码中指定活动配置文件,你想从命令行env var传递它。因此不需要做一个@ActiveProfiles – user5324782