2013-11-01 110 views
0

我想更改文件类从哪个文件类获得它们。
我的班级现在这个样子:Junit替换属性

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");   
} 

而且whyle测试我想性能,从另一个文件中加载。
这是Apache的骆驼的应用程序,所以我有这个现在:

public class ConverterTest { 
    @Override 
    protected RouteBuilder createRouteBuilder() throws Exception { 
     return new MyClass(); //--> Here i must load from another file    
    } 

    @Test 
    // test  
} 

才能实现这一目标?

回答

1

只是通过属性文件名MyClass的构造

public MyClass(String propsFile) throws IOException { 
    loadProperties(propsFile); 
} 
+0

它将如何有效的呢?我将仅使用此构造函数进行测试。但我想知道是否有可能做到这一点,而不需要添加任何东西到我的主类。 – qiGuar

0

也有一些是可以这样做:

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(); 

它涉及代码的一个小小的改变,但它可能不是什么大事......取决于你的项目。

0

可以说,最简洁的解决方案是重构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 
    } 
}