有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何测试配置的“键”和“值”。属性文件?

我有一个ReadPropertyFile类,它有一个返回类型string的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中。属性文件? testConfig的内容。特性如下: 文件\u NAME=D:/刷新\u数据\u每日/所有\u色调\u发布\u excel。xlsx


共 (1) 个答案

  1. # 1 楼答案

    如果文件中未定义密钥, 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"));
    }