码云地址
@TestPropertySource可以用来覆盖掉来自于系统环境变量、Java系统属性、@PropertySource的属性。
同时@TestPropertySource(properties=...)
优先级高于@TestPropertySource(locations=...)
。
利用它我们可以很方便的在测试代码里微调、模拟配置(比如修改操作系统目录分隔符、数据源等)。
例子1: 使用Spring Testing工具
我们先使用@PropertySource将一个外部properties文件加载进来,PropertySourceConfig:
@Configuration
@PropertySource("classpath:me/chanjar/annotation/testps/ex1/property-source.properties")
public class PropertySourceConfig {
}
file: property-source.properties
foo=abc
然后我们用@TestPropertySource覆盖了这个property:
@TestPropertySource(properties = { "foo=xyz" ...
最后我们测试了是否覆盖成功(结果是成功的):
@Test
public void testOverridePropertySource() {
assertEquals(environment.getProperty("foo"), "xyz");
}
同时我们还对@TestPropertySource做了一些其他的测试,具体情况你可以自己观察。为了方便你观察@TestPropertySource对系统环境变量和Java系统属性的覆盖效果,我们在一开始打印出了它们的值。
源代码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 systemEnvironment = ((ConfigurableEnvironment) environment).getSystemEnvironment();
System.out.println("=== System Environment ===");
System.out.println(getMapString(systemEnvironment));
System.out.println();
System.out.println("=== Java System Properties ===");
Map 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 map) {
return String.join("\n",
map.keySet().stream().map(k -> k + "=" + map.get(k)).collect(toList())
);
}
}
例子2: 使用Spring Boot Testing工具
@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 {
// ...
}
参考文档
- Spring Framework Testing
- Spring Boot Testing
- Context configuration with test property sources