7

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.

Michal Kordas
  • 9,161
  • 7
  • 42
  • 81
  • What type is your `ScheduledFuture` intended to be bound to in your actual code? – Makoto Dec 26 '15 at 20:37
  • It is `ScheduledFuture>`, as I'm submitting just `Runnable`. – Michal Kordas Dec 26 '15 at 20:39
  • If this particular test functions fine then, I wouldn't worry about it too much. There may be a way to remove the warning if it's type-bound to `Object`, but I doubt that this would be worth changing. Could you paste the specific test and the test code so that we could replicate it in our own environments? Just enough to replicate the warning will do. – Makoto Dec 26 '15 at 20:42
  • @Makoto I've updated test with mock declaration, I think it should be enough to replicate. I cannot have warning here, as I'm compiling project in environment where all compiler warnings are prohibited. – Michal Kordas Dec 26 '15 at 20:45
  • Well...that's unfortunate. Okay then, I see the plight. – Makoto Dec 26 '15 at 20:46

2 Answers2

9

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)
    );
Michal Kordas
  • 9,161
  • 7
  • 42
  • 81
0

Use the annotation on method level.

@SuppressWarnings("unchecked")
Rzv Razvan
  • 2,012
  • 1
  • 11
  • 17