How to set environment variable or system property in spring tests?
You can initialize the System property in a static initializer:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext {
static {
System.setProperty("myproperty", "foo");
}
}
The static initializer code will be executed before the spring application context is initialized.
One can also use a test ApplicationContextInitializer to initialize a system property:
public class TestApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext>
{
@Override
public void initialize(ConfigurableApplicationContext applicationContext)
{
System.setProperty("myproperty", "value");
}
}
and then configure it on the test class in addition to the Spring context config file locations:
@ContextConfiguration(initializers = TestApplicationContextInitializer.class, locations = "classpath:whereever/context.xml", ...)
@RunWith(SpringJUnit4ClassRunner.class)
public class SomeTest
{
...
}
This way code duplication can be avoided if a certain system property should be set for all the unit tests.
All of the answers here currently only talk about the system properties which are different from the environment variables that are more complex to set, esp. for tests. Thankfully, below class can be used for that and the class docs has good examples
EnvironmentVariables.html
A quick example from the docs, modified to work with @SpringBootTest
@SpringBootTest
public class EnvironmentVariablesTest {
@ClassRule
public final EnvironmentVariables environmentVariables = new EnvironmentVariables().set("name", "value");
@Test
public void test() {
assertEquals("value", System.getenv("name"));
}
}
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource
in the Spring docs and Javadocs.