java - 如何测试config.properties文件的 "key"和 "value"?

标签 java testing junit4 properties-file

我有一个 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/

相关文章:

java - Junit 最佳实践 : Public method calling multiple private methods

java - 包装类提供的静态方法是否经常使用?

java - LWJGL grabbed mouse - 如果应用程序挂起或使用抓取的鼠标命中断点时进行调试

javascript - Node.js:如何使用 proxyquire 替换 neo4j-driver 依赖

spring - 在 Spring 3.1 中使用单独的 persistence.xml 文件进行生产和测试

testing - 如何让 WebDriver 解除 Firefox 安全警报?

java - 为什么我的 Spring JUnit 测试规则没有运行?

java - 我需要 "beginning android games"代码的解释

java - 如何从 JSP 刷新/访问模型

java - 如何自动为@SuiteClasses创建列表