如何模拟和验证在 child class 中调用的 ScheduledExcecutorService 方法

How to Mock and Verify a ScheduledExcecutorService's method being called in child class

我有一个基础 class,看起来像这样:

public abstract class BaseClass implements Runnable {
 final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

 @Override
 public void run() {
     someFunction();
 }
 protected abstract void someFunction();
}

然后我有一个 child class 像这样的东西:

public class ChildClass extends BaseClass {
 functionNeedsToBeTested() {
  scheduler.scheduleAtFixedRate(this, 0L, 5L, TimeUnit.HOURS)
 }
 someFunction() {
  //Does Something
 }
}

现在问题来了,当我尝试编写测试时我无法验证 scheduleAtFixedRate 方法的调用。我的测试看起来像这样:

@RunWith(MockitoJUnitRunner.class)
public class TestClass {
 @Mock
 private ScheduledExecutorService scheduler;

 @InjectMocks
 private ChildClass obj;

 @Test
 public void testFunc() {
   obj.functionNeedsToBeTested();
   Mockito.verify(scheduler).scheduleAtFixedRate(Mockito.any(ChildClass.class, Mockito.anyLong(), Mockito.anyLong(), Mockito.any(TimeUnit.class)));
 }
}

测试给我这个错误:

junit.framework.AssertionFailedError:
    Wanted but not invoked:
    scheduler.scheduleAtFixedRate(
        <any>,
        <any>,
        <any>,
        <any>
     );

在您的测试中,创建了一个模拟调度程序,但它没有被被测对象使用。

如果注入调度程序,而不是在基础 class 中实例化调度程序,则可以使方法可测试。您可以要求调度程序作为 BaseClass 构造函数的参数,例如