问题
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