为方法编写单元测试的最佳方式是什么,例如我的 setProperties
(见下文),它使用 private
配置变量 (配置
)。我尝试但未能使用反射和 Makito 覆盖它,但没有成功。我意识到更改设计以使代码更易于测试是最好的,但我想在重构代码之前创建一些单元测试。
public class MainClass {
private final java.lang.String config = "app.properties";
public TestClass() {
try {
setProperties();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setProperties() throws Exception {
try {
InputStream input = new BufferedInputStream(new FileInputStream(config));
..
..
} catch (Exception exception) {
throw exception;
}
}
}
最佳答案
通过提取带有接受输入流的参数的方法来进行一点重构。从旧方法中调用这个新方法(可能是受包保护的)。针对新方法编写测试。然后进行更多重构。
关于java - 作为重构之前的初始步骤,通过重写私有(private)类变量来测试方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167745/