java如何模拟加载属性文件的服务?
我没有很多模拟测试的经验
我编写了一个从属性文件加载代码的服务。这个很好用。现在我想为这个服务编写单元测试,但不知怎么的,它不起作用了,出了什么问题以及如何修复它?下面是我的服务类+单元测试类和属性文件
public class PhoneCodeService {
private static final Logger LOG = LoggerFactory.getLogger(PhoneCodeService.class);
private static final String PROPERTY_FILE_NAME = "phone-code.properties";
private final Map<String, String> phoneCodes;
private final Properties properties = new Properties();
/**
* Default constructor
*/
public PhoneCodeService() {
try {
readPhoneCodesFromPropertyFile();
} catch (IOException e) {
LOG.debug("Could not read property file " + PROPERTY_FILE_NAME);
}
Map<String, String> map = new HashMap<String, String>();
for (String key : properties.stringPropertyNames()) {
map.put(key, properties.getProperty(key));
}
phoneCodes = map;
}
public String getPhonecode(final String input) {
String code = phoneCodes.get(input);
return code;
}
private void readPhoneCodesFromPropertyFile() throws IOException {
InputStream inputStream = null;
try {
inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(PROPERTY_FILE_NAME);
if (inputStream == null) {
throw new FileNotFoundException("property file is missing");
}
properties.load(inputStream);
} finally {
IOUtils.closeQuietly(inputStream);
}
}
}
单元测试类
public class PhoneCodeServiceTest {
@Mock
private PhoneCodeService phoneCodeService;
@Before
public void setUp() {
initMocks(this);
when(phoneCodeService.getPhonecode("86101")).thenReturn("984");
}
@Test
public void testNull() {
assertEquals(null, phoneCodeService.getPhonecode(null));
}
@Test
public void testCodes() {
final String[] CODES = {"86101"};
for (String code : CODES) {
assertEquals("984", phoneCodeService.getPhonecode(code));
}
}
}
我的属性文件示例
000=1
001=2
002=3
003=4
004=5
# 1 楼答案
我有点惊讶。从你的代码来看,你更像是在测试模拟框架,而不是你的代码。代码中没有任何内容被执行
在这种情况下,更传统的测试方法将更有益
创建一个名为phone code的测试资源文件。包含测试值的属性 在测试期间,该文件必须在类路径中可用
测试PhoneCodeService而不去模仿它
然后按照以下步骤进行测试:
为了实现100%的代码覆盖率,您的类需要一种方法来向PhoneCodeService提供一个不存在的文件