如何在java中为ScheduledThreadPoolExecutor 编写junit?

How to write junit for ScheduledThreadPoolExecutor in java?

我有一个 java class 正在使用 ScheduledThreadPoolExecutor 运行 job.I 已经尝试用 mockto 编写 junit 测试。但它没有调用 运行nable 运行 method.Kindly 帮助

示例:

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
}
}

你从外部提供执行器然后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));
  }
}

通过这种方式,您可以确保 class 在预期时间安排可运行。如果你想确保 runnable 的行为,你可以使用 ArgumentCaptor,但我不知道你将如何验证 System.out.println().