我有一个 ReadPropertyFile 类,它有一个返回类型为字符串的方法 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.properties文件中? testConfig.properties的内容如下: FILE_NAME=D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx
最佳答案
如果key没有在文件中定义,
getProperties
方法返回 null
。
如果键存在但没有值,
getProperties
方法返回一个空字符串。
您在文件中捕获和抛出异常的方式没有多大意义。
您可以将您的方法简化为:
public String getPropertyFor(String key) {
return properties.getProperty(key);
}
鉴于 testConfig.properties
中的内容:
FILE_NAME = D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx
empty.test =
您可以像这样对不同的情况进行单元测试:
private String getProperty(String key) {
new ReadPropertyFile("testConfig.properties").getPropertyFor(key)
}
@Test
public void testMissingKey() {
assertNull(getProperty("nonexistent"));
}
@Test
public void testEmptyKey() {
assertEquals("", getProperty("empty.prop"));
}
@Test
public void testValue() {
assertEquals("D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx", getProperty("FILE_NAME"));
}
关于java - 如何测试config.properties文件的 "key"和 "value"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33017584/