Set System Properties or Environment Variables Before Property Placeholder with SpringJunit4ClassRunner

java, junit, properties, spring, unit-testing

Solution

Thinking of ,

- Extending `SpringJUnit4ClassRunner` and setting the system property `configOverride` in its constructor/initialization block

- Then passing `ExtendedSpringJUnit4ClassRunner` to `@RunWith`

Problem

I have a main app-context.xml that defines a property placeholder with two locations: default properties file and an optional override file: ``` <context:property-placeholder location="classpath:config.properties,${configOverride}" ignore-resource-not-found="true" /> ``` The optional override location allows specifying another properties file (e.g. "-DconfigOverride=file:/home/app/config.properties") with only the properties that should be overridden. For my unit tests, I'm using a test context that imports app-context.xml: ``` @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:test-context.xml"}) public class UserServiceTest { ... } ``` How can I set system properties or environment variables within the application before the application context is loaded? I would like to achieve the same effect as setting "-DconfigOverride=classpath:testConfig.properties" across all test classes without having to specify a command line arg, if possible.

Original source