[英]How to test only the “key” from .properties file in java using Junit
我有一个类ReadPropertyFile,它包含名为getPropertyFor的方法,该方法返回给定键的值作为参数。 我正在以键作为输入参数从其他类调用getPropertyFor()方法。 我的属性filetestConfig.properties(文件名)的内容是:FILE_NAME = D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx
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) {
return properties.getProperty(key);
}
}
@Test
public void testFilePathValueInConfigFile(){
assertEquals(propertyFileObj.getPropertyFor(keyForFilePath), "D:/Refreshed_data_daily/all_hue_posts_in_excel.xlsx");
}
上面的测试用例是检查该函数返回的值是否正确。 如何检查密钥是否正确? 什么是可能的测试用例来测试密钥。 而且我不想出于测试目的更改我的testConfig.properties文件。 我需要帮助,我是Java Junit测试的新手。
如果要测试属性文件中是否存在密钥,则有两种方法:
如果已通过属性构造函数为属性指定了dafault值并带有一些预定义的值,并且如果尝试获取该键且该键不存在,则将获得此默认值。 在这种情况下,您必须检查您的收益是否等于此默认值。
但是,如果您未提供默认值,则由于Propery#getProperty的javadoc,您可以在其返回值上直接使用asserNotNull:
在此属性列表中使用指定的关键字搜索属性。 如果在此属性列表中找不到该键,则将递归检查默认属性列表及其默认值。 如果找不到该属性,则该方法返回null。
但是,在进行单元测试的情况下,您必须提供许多不同的属性来测试方法或类的所有可能的行为。
假设您有一个名为myprop.properties的属性文件:
key1=value1
key2=
key3
您可以编写以下4个测试来检查属性是否缺失。 如在不同情况下所示,当您调用properties.get(“ key4”)时,只有不在属性文件中的键(key4)会返回null 。 对于key1,它返回value1。 如果是key2和key3,则返回空字符串。
因此,要检查属性文件中是否存在密钥,可以使用Assert.assertNull(properties.get(KEY_NAME)) 。
public class CheckPropertiesTest {
Properties properties = new Properties();
@Before
public void init() throws IOException {
properties.load(CheckProperties.class.getResourceAsStream("/myprop.properties"));
}
@Test
public void test1() {
Assert.assertNotNull(properties.get("key1"));
}
@Test
public void test2() {
Assert.assertNotNull(properties.get("key2"));
}
@Test
public void test3() {
Assert.assertNotNull(properties.get("key3"));
}
@Test
public void test4() {
Assert.assertNull(properties.get("key4"));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.