Mocking ScheduledExecutorService.scheduleWithFixedDelay(…) is returning null

蓝咒 提交于 2020-07-21 04:19:33

问题


In my unit test, I've injected a mocked instance of the ScheduledExecutoryService class into the class that I'm trying to test so that when the scheduleAtFixedRate(...) method is called, it returns a mocked Future. For some reason though, it's always returning null. Any ideas ?

Application code:

Future<?> t = 
scheduledExecutorService.scheduleAtFixedRate(this, 10, 10, TimeUnit.SECONDS);

Test code:

@Mock ScheduledExecutorService scheduledExecutorService;
@Mock ScheduledFuture<?> t;

Mockito.doReturn(t).when(scheduledExecutorService).scheduleWithFixedDelay(
any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class));

回答1:


You are passing Integers (and probably that is the definition of the method parameters) though you are expecting Long values.

Change to:

Mockito.doReturn(t).when(scheduledExecutorService).scheduleWithFixedDelay(
any(Runnable.class), anyInt(), anyInt(), any(TimeUnit.class));



回答2:


Your application code is using scheduleAtFixedRate, but your test code is only mocking method scheduleWithFixedDelay.



来源:https://stackoverflow.com/questions/43786137/mocking-scheduledexecutorservice-schedulewithfixeddelay-is-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!