我有一个类
public class Authentication {
private Timer timer;
public Authentication(){
// constructor
}
public void authenticate(){
// Initialize timer in this method
timer = new RouterTimer(FAKE_PARAM);
testingMethod();
}
@VisibleForTesting
void testingMethod(){
timer.method();
// other stuff
}
}
我有一个 Timer 对象作为类属性,但它没有在构造函数中初始化,而是在authenticate() 中初始化。
我正在为 testingMethod()
编写单元测试,但测试失败,因为 timer
为 null 并且调用 method() 将抛出 NullPointerException。我无法使用类的构造函数初始化计时器。我无法调用 authenticate()
进行初始化,因为该方法将调用 testingMethod()
。
在这种情况下我该如何模拟或做其他事情?
最佳答案
为什么要尝试测试私有(private)方法?将代码拆分为逻辑部分并单独测试它们。此外,您还违反了 SRP ( https://en.wikipedia.org/wiki/Single-responsibility_principle )。方法authenticate() 不应该初始化任何东西。
关于java - 如何模拟其对象在测试方法之外初始化的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64347725/