如何模拟和验证在子类中调用的ScheduledExecutorService方法

问题描述 投票:1回答:1

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

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

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

然后我有一个像这样的子类:

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>
     );
java unit-testing inheritance mockito scheduledexecutorservice
1个回答
3
投票

在测试中,会创建一个模拟调度程序,但测试对象不会使用它。

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

© www.soinside.com 2019 - 2024. All rights reserved.