让我们假设我有这样的方法
public void scheduleCleanup(String parameter) {
final SomeObject someObject = new SomeObject(parameter);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.schedule((Runnable) () -> cleanupService.startCleanup(someObject),
CLEANUP_TIMEOUT_SEC, TimeUnit.SECONDS);
}
这意味着在cleanupService.startCleanup(someObject)
之后调用CLEANUP_TIMEOUT_SEC
实际上来自某个属性文件。
对我而言,很明显我可以创建SomeObject
并为cleanupService.startCleanup(someObject)
编写单元测试,但我如何使用scheduleCleanup
方法?
答案 0 :(得分:1)
我想您要避免在单元测试中使用/调用ScheduledThreadPoolExecutor。我会用ScheduledExecutorService替换ScheduledThreadPoolExecutor并将它注入到类中:
@Inject ExecutorService executor;
public void scheduleCleanup(String parameter) {
final SomeObject someObject = new SomeObject(parameter);
executor.schedule((Runnable) () -> cleanupService.startCleanup(someObject),
CLEANUP_TIMEOUT_SEC, TimeUnit.SECONDS);
}
然后,您只需验证在适当的位置调用了executor.schedule(Runnable, long, TimeUnit)
。