ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor

假设我有一个这样的方法

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方法怎么办?


我以为我需要模拟它,但是在这种情况下您该如何做呢?
是否可以避免嘲笑?在这种情况下,最佳方法是什么?

最佳答案

我想您想避免在单元测试中使用/调用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)

关于java - ScheduledThreadPoolExecutor的单元测试,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35892264/

10-09 00:40