Config.properties returns 仅调用两次时的值

Config.properties returns value only when called twice

我有一个正在 运行 测试的程序,并且我有一个尝试访问 config.properties 文件值的特定方法。我第一次调用它时 returns 为空,第二次调用后只有 returns 一个值,我不明白为什么。

这是我的测试,我在其中两次调用 getHostProp() 方法

@Test
public void testHost() throws Exception {

    //when
    notMocked.getHostProp();
    assertEquals("tkthli.com", notMocked.getHostProp());
}

以及正在测试的 class 中的方法

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.");

    }
}

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

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

希望我回答了你的问题

你能试试这个吗...

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

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

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