java如何测试配置的“键”和“值”。属性文件?
我有一个ReadPropertyFile类,它有一个返回类型string的getPropertyFor()方法(它是作为参数传递的键对应的值)。我需要帮助来使用Junit测试getPropertyFor()方法的值和键
public class ReadPropertyFile {
private Properties properties;
public ReadPropertyFile(String propertyFileName) {
properties= new Properties();
try {
properties.load(new FileReader(propertyFileName));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getPropertyFor(String key) {
String value = properties.getProperty(key);
if(value == null) {
try {
throw new Exception(key + " not found!");
} catch (Exception e) {
e.printStackTrace();
}
}
return value;
}
}
我编写了以下测试用例来测试所提供的键的值
如何测试“key”是否包含在testconfig中。属性文件? testConfig的内容。特性如下: 文件\u NAME=D:/刷新\u数据\u每日/所有\u色调\u发布\u excel。xlsx
# 1 楼答案
如果文件中未定义密钥,
getProperties
方法返回null
。 如果密钥存在但没有值,getProperties
方法返回一个空字符串。 在文件中捕获并抛出异常的方式没有多大意义。 您可以将方法简化为:鉴于
testConfig.properties
中的内容:您可以像这样对不同的情况进行单元测试: