Search code examples
javamockitounchecked

Avoiding unchecked warnings when using Mockito


I'd like to mock a call on ScheduledExecutorService to return mock of ScheduledFuture class when method schedule is invoked. The following code compiles and works correctly:

    ScheduledExecutorService executor = Mockito.mock(ScheduledExecutorService.class);
    ScheduledFuture future = Mockito.mock(ScheduledFuture.class);
    Mockito.when(executor.schedule(
        Mockito.any(Runnable.class),
        Mockito.anyLong(),
        Mockito.any(TimeUnit.class))
    ).thenReturn(future); // <-- warning here

except that I'm getting unchecked warning in the last line:

found raw type: java.util.concurrent.ScheduledFuture
  missing type arguments for generic class java.util.concurrent.ScheduledFuture<V>

 unchecked method invocation: method thenReturn in interface org.mockito.stubbing.OngoingStubbing is applied to given types
  required: T
  found: java.util.concurrent.ScheduledFuture

unchecked conversion
  required: T
  found:    java.util.concurrent.ScheduledFuture

Is it possible to somehow avoid these warnings?

Code like ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class); doesn't compile.


Solution

  • All warnings go away when alternative way of mock specification is used:

        ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class);
        Mockito.doReturn(future).when(executor).schedule(
            Mockito.any(Runnable.class),
            Mockito.anyLong(),
            Mockito.any(TimeUnit.class)
        );