简体   繁体   中英

spring @Conditional in SpringJUnit4ClassRunner

I need to load test properties in production environment when tests is performing by SpringJUnit4ClassRunner.

I'm using @Conditional in my spring context to define test/production properties files, like:

@Configuration
public class ContextResource {

@Bean
@Conditional(TestApplicationConfiguration.class)
public static PropertySourcesPlaceholderConfigurer testProperties() {
    PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    Resource [] resources = new Resource[] {
            new ClassPathResource("properties/constants/constants-test.properties")
    };

    placeholderConfigurer.setLocations(resources);
    return placeholderConfigurer;
}

@Bean
@Conditional(ProductionApplicationConfiguration.class)
public static PropertySourcesPlaceholderConfigurer productionProperties() {
    PropertySourcesPlaceholderConfigurer placeholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    Resource [] resources = new Resource[] {
            new ClassPathResource("properties/constants/constants.properties")
    };

    placeholderConfigurer.setLocations(resources);
    return placeholderConfigurer;
}

Also i'm using test with

@RunWith(SpringJUnit4ClassRunner.class)

When ProductionApplicationConfiguration.class returned false, constants-test.properties is loading and it's normal, but how can I tell my tests to load test properties even if ProductionApplicationConfiguration.class returned true ?

Thank you in advance!

You may use different resource (src\\main\\java\\resources and src\\test\\java\\resources) with same names on property files for production and test mode. By default, tests try use property from src\\test\\java\\resources, but if they don't find it, then they will use property from src\\main\\java\\resources.

in 13 intelliji you can mark testResources in module setting.

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