Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
Michal Kordas Avatar asked Dec 26 '15 20:12

Michal Kordas


People also ask

How can I avoid unchecked cast warnings?

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.

What is unchecked warning in Java?

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.

What does stubbing mean in Mockito?

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.

What can be mocked in Mockito?

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.


1 Answers

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)
    );
like image 73
Michal Kordas Avatar answered Nov 03 '22 01:11

Michal Kordas