51Testing软件测试论坛
标题: Spring、Spring Boot和TestNG测试指南 [打印本页]
作者: 测试积点老人 时间: 2018-12-26 09:26
标题: Spring、Spring Boot和TestNG测试指南
例子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<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())
- );
- }
- }
复制代码 例子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 {
- // ...
- }
复制代码
欢迎光临 51Testing软件测试论坛 (http://bbs.51testing.com/) |
Powered by Discuz! X3.2 |