java - 如何模拟其对象在测试方法之外初始化的方法?
问题描述
我有一堂课
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()
.
在这种情况下,我该如何模拟或做其他事情?
解决方案
你为什么要测试私有方法?将您的代码拆分为逻辑部分并分别测试它们。此外,您正在破坏 SRP ( https://en.wikipedia.org/wiki/Single-responsibility_principle )。方法 authenticate() 不应该初始化任何东西。
推荐阅读
- haskell - Haskell scotty 和持久性休息 API
- winapi - 如何仅使用标准库写入 Windows 上的备用屏幕缓冲区?
- sql - 汇总其余值
- vue.js - 更改页面时禁用过渡
- angular - 具有 ngx-translate 依赖项的 Angular 6 单元测试
- profiling - Class::DBI - 它会加载所有表吗?
- delphi - FireDAC“无法完成对主机的网络请求”
- wxwidgets - wx.Grid 和 ScrolledWindows
- javascript - 如何使用 react-swipe-card 在 React 中构建可堆叠的卡片?
- python - Python 'dict' 对象没有属性 'status'