简体   繁体   中英

How to set environment variable dynamically in spring test

I am trying to run spring-test cases with spring-boot. My test class looks like as follows

@ContextConfiguration(initializers = TestContextInitializer.class)
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {TestServiceApplication.class})

public class SampleTest {
    @org.junit.Test
    public void getContactsByName() throws Exception {
    }

}

While my configuration class looks like

public class TestContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
        System.setProperty("DATA_DB_URL","some_url");
        System.setProperty("DATA_DB_USER","some_user");
        System.setProperty("DATA_DB_PASSWORD","some_password");
        System.setProperty("DATA_DB_POOL_SIZE","2");
        System.setProperty("DATA_DB_ROW_PREFETCH_SIZE","50");
    }
}

Everything is working fine but I have problem. I can not check-in PASSWORD in the source code as my company policy. How can I externalize the password so that I don't have to check it in.

Just use environment variables. Or there is the @PropertySource annotation for using different properties for tests.

But on another note you really shouldn't use System Properties like that. The System properties is for the system, what's the OS, time system, language, etc. It shouldn't be anything to do with your application. This also introduces global shared state. Although you probably don't if you were to start running your tests in parallel they would break sporadically if you change these values from test to test. You could run into other problems such as the a situation where you need the property of DATA_DB_USER to be different for 2 different components.

You can supply the password (or any Spring property) at runtime via System or Environment or Command Line variables. All of those sources are (a) defined at runtime and (b) external to your code base.

For example:

  • export password=...; java -jar app.jar export password=...; java -jar app.jar sets an environment variable named password which will then be present in your Spring Environment
  • java -Dpassword=... -jar app.jar sets a JVM system parameter which will then be present in your Spring Environment
  • java -jar myapp.jar --password=... sets a command line variable which will then be present in your Spring Environment

You can even source a property from JNDI.

More details in the docs .

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