【问题标题】:Config.properties returns value only when called twiceConfig.properties 仅在调用两次时才返回值
【发布时间】: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" 会执行的场景。

标签: java testing junit


【解决方案1】:

你能不能试试这个...

if(foundFile()) {
   return prop.getProperty("DAILY-DMS.instances");
}

prop 对象仅在 foundFile() 调用后填充,但是您正在读取前一行中的数据。

另外,除非您在运行时更新配置文件,否则我建议您阅读属性文件之一并将其存储在某个静态对象或单例中。这样您就可以避免任何进一步的文件读取。只是一个想法..

【讨论】:

  • 啊,我明白了。 @redflar3 如果它在我填充数据之前尝试读取数据,那么它为什么不给我一个空指针异常?
  • @ralphie9224 没有任何东西试图取消对 null 的引用。
  • @ralphie9224 [docs.oracle.com/javase/7/docs/api/java/lang/… 此页面解释了何时可能发生 NPE。代码中的一种可能情况是 assertTrue 语句。该语句必须检查参数的值以检查是否相等,并且可能会抛出 NPE。但是assertTrue 在内部使用 String#equals 实现。如果您检查源代码,您会发现它忽略了不是String 实例的任何对象(作为参数传递)。因此 null 引用的字符串对象将被忽略并返回 false。
【解决方案2】:

您没有加载您的属性 'prop' 并试图获取 "DAILY-DMS.instances" 属性!
它第二次起作用的原因是您的方法 foundFile() 实际上将属性加载到 'prop' 成员变量并在您第一次调用 getHostProp 期间返回 true () 方法。

在第二次调用期间,您的 'prop' 成员变量已准备好加载值。

希望我回答了你的问题

【讨论】:

  • @ralphie9224 - 它不会抛出 NullPointerException,因为您已经像这样初始化了“prop”成员变量:“Properties prop = new Properties();”因此,您现在可以从“prop”访问任何方法。如果您阅读了我上面的答案,那么您就可以理解发生了什么。您可以从 java api-docs.oracle.com/javase/7/docs/api/java/util/Properties.html 找到有关 Properties.java 如何工作的更多信息
猜你喜欢
  • 1970-01-01
  • 2016-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
相关资源
最近更新 更多