Set system properties or environment variables in front of the property owner using SpringJunit4ClassRunner

I have a main app-context.xml that defines a property placeholder with two locations: a default property file and an additional override file:

<context:property-placeholder
        location="classpath:config.properties,${configOverride}"
        ignore-resource-not-found="true" />

An optional override location allows you to specify a different property file (for example, "-DconfigOverride = file: /home/app/config.properties") with only properties that need to be overridden.

For my unit tests, I use a test context that imports app-context.xml:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class UserServiceTest {
    ...
}

? , "-DconfigOverride = classpath: testConfig.properties" arg, .

+5
4

,

  • SpringJUnit4ClassRunner configOverride /
  • ExtendedSpringJUnit4ClassRunner @RunWith
+5

@BeforeClass, , .

@BeforeClass
public static void setSystemProps() {
    System.setProperty("configOverride", "yourVal");
}
+15

- unit test. , "configOverride" (. AhamedMustafaM ) ( ).

testContext.xml:

<!-- import the main app context -->
<import resource="classpath:appContext.xml" />

<!-- this is the line i added -->
<context:property-placeholder order="-999"
        location="classpath:testConfig.properties"
        ignore-unresolvable="true" />

order = "- 999", -. "ignore-unresolvable" "true" .

+3

My problem was similar, but I wanted to set the environment variable spring.profiles.active, and it turned out that I just needed to drop it @ActiveProfiles()with the values ​​that I wanted to get on the test itself.

0
source

All Articles