说明
目前还是一个半成品。存在的问题: 需要先通过PropertiesClass构造方法来导入一个dummy的配置文件,然后再修改具体的Propery值。
这对于有大量需要初始化配置的应用来说,不太实用。需要进一步研究如何去mock
getResourceAsStream来完成属性的动态设置。
测试用例
//loading from a real property file
@Test
public void testPropertiesClass() {
PropertiesClass pc= new PropertiesClass();
assertEquals("111",pc.print("aaa"));
}
//loading from a defult file and then modify the properties.
@Test
public void testMockPropertiesClassWithDummy() {
Properties mockProperties =PowerMockito.mock(Properties.class);
PropertiesClass propertiesClass = new PropertiesClass();
Whitebox.setInternalState(propertiesClass, "prop", mockProperties);
PowerMockito.when(mockProperties.getProperty("aaa")).thenReturn("8888");
assertEquals("8888",propertiesClass.print("aaa"));
}
SUT:
public class PropertiesClass {
private Properties prop= new Properties();
public PropertiesClass() {
load();
}
public void load() {
prop= new Properties();
InputStream in;
try {
in = this.getClass().getResourceAsStream("a.properties");
prop.load(in);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String print(String key) {
return prop.getProperty(key);
}
}