问题
单元测试的代码中,有从application.properties中读取的变量。
但在单元测试中,无法读取配置文件,变量默认为空,导致单元测试不通过。如何在单元测试中mock配置文件中的变量呢?
解决
待测试的类
public class AbcService {
// 从配置文件中读取,如单元测试中不mock,会为空
@Value("test.config")
private String testConfig;
public void demo() throws Exception {
String key = "lalala" + testConfig;
...
...
}
}
单元测试
@RunWith(PowerMockRunner.class)
@PrepareForTest({HttpClientUtil.class})
public class AbcServiceTest extends PowerMockTestCase {
@InjectMocks
private AbcService abcService;
@Test
public void testDemo() throws Exception {
// 将testConfig的值mock为123
ReflectionTestUtils.setField(abcService, "testConfig", "123");
...
...
}
}