How to set environment variable dynamically in spring test

Ashish picture Ashish · Sep 19, 2017 · Viewed 9.5k times · Source

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.

Answer

Derrops picture Derrops · Sep 22, 2017

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.