ScheduledThreadPoolExecutor的单元测试

时间:2016-03-09 12:56:55

标签: java unit-testing junit mocking

让我们假设我有这样的方法

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方法?

  1. 我认为我需要嘲笑它,但在这种情况下你怎么做呢?
  2. 是否有可能避免嘲笑,在这种情况下最好的方法是什么?

1 个答案:

答案 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)