Github地址html
@TestPropertySource能夠用來覆蓋掉來自於系統環境變量、Java系統屬性、@PropertySource的屬性。java
同時@TestPropertySource(properties=...)
優先級高於@TestPropertySource(locations=...)
。git
利用它咱們能夠很方便的在測試代碼裏微調、模擬配置(好比修改操做系統目錄分隔符、數據源等)。github
咱們先使用@PropertySource將一個外部properties文件加載進來,PropertySourceConfig:spring
@Configuration @PropertySource("classpath:me/chanjar/annotation/testps/ex1/property-source.properties") public class PropertySourceConfig { }
file: property-source.properties foo=abc
而後咱們用@TestPropertySource覆蓋了這個property:api
@TestPropertySource(properties = { "foo=xyz" ...
最後咱們測試了是否覆蓋成功(結果是成功的):ide
@Test public void testOverridePropertySource() { assertEquals(environment.getProperty("foo"), "xyz"); }
同時咱們還對@TestPropertySource作了一些其餘的測試,具體狀況你能夠本身觀察。爲了方便你觀察@TestPropertySource對系統環境變量和Java系統屬性的覆蓋效果,咱們在一開始打印出了它們的值。spring-boot
源代碼TestPropertyTest:工具
@ContextConfiguration(classes = PropertySourceConfig.class) @TestPropertySource( properties = { "foo=xyz", "bar=uvw", "PATH=aaa", "java.runtime.name=bbb" }, locations = "classpath:me/chanjar/annotation/testps/ex1/test-property-source.properties" ) public class TestPropertyTest extends AbstractTestNGSpringContextTests implements EnvironmentAware { private Environment environment; @Override public void setEnvironment(Environment environment) { this.environment = environment; Map<String, Object> systemEnvironment = ((ConfigurableEnvironment) environment).getSystemEnvironment(); System.out.println("=== System Environment ==="); System.out.println(getMapString(systemEnvironment)); System.out.println(); System.out.println("=== Java System Properties ==="); Map<String, Object> systemProperties = ((ConfigurableEnvironment) environment).getSystemProperties(); System.out.println(getMapString(systemProperties)); } @Test public void testOverridePropertySource() { assertEquals(environment.getProperty("foo"), "xyz"); } @Test public void testOverrideSystemEnvironment() { assertEquals(environment.getProperty("PATH"), "aaa"); } @Test public void testOverrideJavaSystemProperties() { assertEquals(environment.getProperty("java.runtime.name"), "bbb"); } @Test public void testInlineTestPropertyOverrideResourceLocationTestProperty() { assertEquals(environment.getProperty("bar"), "uvw"); } private String getMapString(Map<String, Object> map) { return String.join("\n", map.keySet().stream().map(k -> k + "=" + map.get(k)).collect(toList()) ); } }
@TestPropertySource也能夠和@SpringBootTest一塊兒使用。測試
源代碼見TestPropertyTest:
@SpringBootTest(classes = PropertySourceConfig.class) @TestPropertySource( properties = { "foo=xyz", "bar=uvw", "PATH=aaa", "java.runtime.name=bbb" }, locations = "classpath:me/chanjar/annotation/testps/ex1/test-property-source.properties" ) public class TestPropertyTest extends AbstractTestNGSpringContextTests implements EnvironmentAware { // ... }