我有一个看起来像这样的基类:
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>
);
最佳答案
在您的测试中,创建了一个模拟调度程序,但它未被被测对象使用。
如果注入(inject)调度程序而不是在基类中实例化调度程序,则可以使方法可测试。例如,您可以要求调度程序作为 BaseClass 构造函数的参数
关于java - 如何模拟和验证在子类中调用的 ScheduledExecutorService 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44230609/