【问题标题】:How to write junit for ScheduledThreadPoolExecutor in Java?如何在 Java 中为 ScheduledThreadPoolExecutor 编写 junit?
【发布时间】: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


【解决方案1】:

你从外部提供执行者然后verify

class MyClass {
  private final ScheduledThreadPoolExecutor stp;
  public MyClass(ScheduledThreadPoolExecutor ex) { stp = ex; }

  public void start() {
    stp.scheduleAtFixedRate(executeRunnable(), 2,2, TimeUnit.SECONDS); 
  }
}

class MyTest {
  @Mock
  ScheduledThreadPoolExecutor exec;

  public void testStart() {
    MyClass sut = new MyClass(exec);
    sut.start();
    verify(exec).scheduleAtFixedRate(any(), eq(2), eq(2), eq(TimeUnit.SECONDS));
  }
}

这样,您可以确保课程在预期时间安排可运行文件。如果您想确保可运行的行为,您可以使用ArgumentCaptor,但我不知道您将如何验证System.out.println()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2022-11-04
    相关资源
    最近更新 更多