简体   繁体   中英

Set Spring Unit Test Profile From -D Variables

I have got a test like this

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

The AppConfig is the main config for my app

there are two config class created just fro my unit tests the DEV config class loads test_dev.properties from my src/test/resource/...

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

}

the ProdConfig class loads prod.properties

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

}

I want switch easily between prod and dev by changing the value in the @ActiveProfiles

But I want be able to switch test environment like

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

I have tried

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

it seems the prod always gets picked up

I have seen solution like

@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 ...
    }

but this is would lost the whole point of using the @ContextConfiguration annotation.

I think the switch is

-Dspring.profiles.active=dev

or even as an environment variable

SPRING_PROFILES_ACTIVE=dev mvn install

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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