【发布时间】:2017-06-06 03:15:17
【问题描述】:
我希望能够使用测试属性文件并且只覆盖几个属性。必须覆盖每一个属性会很快变得丑陋。
这是我用来测试我在测试用例中模拟属性和使用现有属性的能力的代码
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyApp.class)
@TestPropertySource(
locations = { "classpath:myapp-test.properties" },
properties = { "test.key = testValue" })
public class EnvironmentMockedPropertiesTest {
@Autowired private Environment env;
// @MockBean private Environment env;
@Test public void testExistingProperty() {
// some.property=someValue
final String keyActual = "some.property";
final String expected = "someValue";
final String actual = env.getProperty(keyActual);
assertEquals(expected, actual);
}
@Test public void testMockedProperty() {
final String keyMocked = "mocked.test.key";
final String expected = "mockedTestValue";
when(env.getProperty(keyMocked)).thenReturn(expected);
final String actual = env.getProperty(keyMocked);
assertEquals(expected, actual);
}
@Test public void testOverriddenProperty() {
final String expected = "testValue";
final String actual = env.getProperty("test.key");
assertEquals(expected, actual);
}
}
我发现的是:
-
@Autowired private Environment env;-
testExistingProperty()和testOverriddenProperty()通过 -
testMockedProperty()失败
-
-
@MockBean private Environment env;-
testMockedProperty()通过 -
testExistingProperty()和testOverriddenProperty()失败
-
有没有办法实现我的目标?
依赖关系:
<spring.boot.version>1.4.3.RELEASE</spring.boot.version>
...
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>${spring.boot.version}</version>
</dependency>
<!-- Starter for testing Spring Boot applications with libraries including JUnit,
Hamcrest and Mockito -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>${spring.boot.version}</version>
</dependency>
【问题讨论】:
-
我假设你想通过只使用一个环境 env 变量来实现这一点,它既可以处理模拟数据,也可以处理真实数据,对吧?
标签: spring unit-testing spring-boot junit mockito