Java Junit替换属性
我想更改Java Junit替换属性,java,junit,Java,Junit,我想更改.properties文件类应该从哪个文件类获取它们。 我的班级现在是这样的: public class MyClass { private String str; public MyClass() throws IOException { loadProperties(); } private void loadProperties() throws IOException { Properties props = new Properties();
.properties
文件类应该从哪个文件类获取它们。我的班级现在是这样的:
public class MyClass {
private String str;
public MyClass() throws IOException {
loadProperties();
}
private void loadProperties() throws IOException {
Properties props = new Properties();
props.load(getClass().getClassLoader().getResourceAsStream("my.properties"));
str= props.getProperty("property");
}
public class ConverterTest {
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new MyClass(); //--> Here i must load from another file
}
@Test
// test
}
我希望从另一个文件加载属性。这是apache camel应用程序,所以我现在有:
public class MyClass {
private String str;
public MyClass() throws IOException {
loadProperties();
}
private void loadProperties() throws IOException {
Properties props = new Properties();
props.load(getClass().getClassLoader().getResourceAsStream("my.properties"));
str= props.getProperty("property");
}
public class ConverterTest {
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new MyClass(); //--> Here i must load from another file
}
@Test
// test
}
这可以实现吗?只需将属性文件名传递给MyClass构造函数即可
public MyClass(String propsFile) throws IOException {
loadProperties(propsFile);
}
你可以做一些事情:
public class MyClass {
private String str;
private String path = "my.properties";
public MyClass() throws IOException {
loadProperties();
}
protected void loadProperties() throws IOException {
Properties props = new Properties();
props.load(getClass().getClassLoader().getResourceAsStream(path));
str= props.getProperty("property");
}
然后,使用以下代码将测试添加到同一个包中:
myClass = new MyClass();
ReflectionTestUtils.setField(path, "otherpathto.properties");
myClass.loadProperties();
它涉及到代码中的一个小改动,但这可能不是什么大问题。。。根据您的项目而定。可以说,最干净的解决方案是重构
MyClass
,删除对Properties
对象的依赖,并通过构造函数注入所需的值。您的案例证明,隐藏的和硬编码的依赖关系使测试复杂化
读取属性文件并将值注入MyClass
的责任可以推回给调用者:
public class MyClass {
private final String str;
public MyClass(String strValue) {
this.str = strValue;
}
// ...
}
public class ProductionCode {
public someMethod() {
Properties props = new Properties();
props.load(getClass().getClassLoader().getResourceAsStream("my.properties"));
String str = props.getProperty("property");
MyClass obj = new MyClass(str);
obj.foo();
}
}
public class ConverterTest {
@Test
public void test() {
String testStr = "str for testing";
MyClass testee = new MyClass(testStr);
testee.foo();
// assertions
}
}
效率有多高?我将仅在测试中使用此构造函数。但我想知道,如果不在我的主课中添加内容,是否有可能做到这一点。