【发布时间】:2022-07-25 22:49:43
【问题描述】:
我有一个使用 ScheduledThreadPoolExecutor 运行作业的 Java 类。我尝试使用 mockto 编写 junit 测试。但它没有调用可运行的运行方法。
例子:
class MyExecutor {
ScheduledThreadPoolExecutor stp = new ScheduledThreadPoolExecutor();
pubilc void start() {// how to write test junit
stp.scheduleAtFixedRate(executeRunnable(), 2,2, TimeUnit.SECONDS);
}
private void executeRunnable() {
new Runnable() {
public void run() {
System.out.println("running");
}
}
}
}
朱尼特
class MyExecutorTest {
public void testStart() {
MyExecutor exec = new MyExecutor();
exec.start();//its not printing from run method
}
}
【问题讨论】:
-
作为一个更元的问题......为什么要测试
ScheduledThreadPoolExecutor类?你不会假设它已经被作者等测试过吗?您只需要测试调度程序执行的您自己的代码。 -
我只需要测试用run方法调用的启动功能?
-
是的,您应该测试您的 run 方法的作用,因为这是您感兴趣的“业务逻辑”和您正在编写的代码。它的调度本质上是由您未编写的第 3 方库处理的样板代码。
-
但作为 junit 功能,它应该调用 .为什么它不打电话
-
exec.start()告诉调度程序运行,您的配置告诉它在初始延迟 2(秒?)后运行。但是......除非您告诉它,否则您的代码不会等待调度程序在 2 秒后运行。 @daniu 的代码看起来正是您所需要的。
标签: java scheduled-tasks threadpoolexecutor