Search code examples
javaspringenvironment-variablesspring-test

How to set environment variable or system property in spring tests?


I'd like to write some tests that check the XML Spring configuration of a deployed WAR. Unfortunately some beans require that some environment variables or system properties are set. How can I set an environment variable before the spring beans are initialized when using the convenient test style with @ContextConfiguration?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
public class TestWarSpringContext { ... }

If I configure the application context with annotations, I don't see a hook where I can do something before the spring context is initialized.


Solution

  • 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.