【发布时间】:2015-06-10 19:22:45
【问题描述】:
我有一个正在运行测试的程序,并且我有一个尝试访问config.properties 文件值的特定方法。第一次调用它返回null,第二次调用后才返回一个值,我不知道为什么。
这是我的测试,其中我调用了两次 getHostProp() 方法
@Test
public void testHost() throws Exception {
//when
notMocked.getHostProp();
assertEquals("tkthli.com", notMocked.getHostProp());
}
以及它正在测试的类中的方法
public class ConfigProperties {
Properties prop = new Properties();
String propFileName = "config.properties";
public String getHostProp() throws IOException {
String host = prop.getProperty("DAILY-DMS.instances");
if(foundFile()) {
return host;
}
return "Error";
}
}
这是我用来检查是否找到 config.properties 的路径的辅助方法。我不确定它会如何影响这一点,但我添加它以防万一有人在其中看到我看不到的东西,这可能会导致问题。
public boolean foundFile() throws IOException {
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
inputStream.close();
return true;
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath.");
}
}
【问题讨论】:
-
因为找不到文件会抛出异常,所以可以忽略检查
if(foundFile){..},直接给fileFound(); return prop.getPr.....。你从foundFile得到的唯一回报是true,所以我看不到return "Error"会执行的场景。