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.
If we can't eliminate the “unchecked cast” warning and we're sure that the code provoking the warning is typesafe, we can suppress the warning using the SuppressWarnings(“unchecked”) annotation. When we use the @SuppressWarning(“unchecked”) annotation, we should always put it on the smallest scope possible.
An unchecked warning tells a programmer that a cast may cause a program to throw an exception somewhere else. Suppressing the warning with @SuppressWarnings("unchecked") tells the compiler that the programmer believes the code to be safe and won't cause unexpected exceptions.
A stub is a fake class that comes with preprogrammed return values. It's injected into the class under test to give you absolute control over what's being tested as input. A typical stub is a database connection that allows you to mimic any scenario without having a real database.
The Mockito. mock() method allows us to create a mock object of a class or an interface. We can then use the mock to stub return values for its methods and verify if they were called. We don't need to do anything else to this method before we can use it.
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)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With