使用 Mockito 时避免未经检查的警告
Avoiding unchecked warnings when using Mockito
我想在调用方法 schedule
时将 ScheduledExecutorService
上的调用模拟为 return 模拟 ScheduledFuture
class。以下代码编译并正常工作:
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
除了我在最后一行收到未经检查的警告:
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
是否有可能以某种方式避免这些警告?
像 ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class);
这样的代码无法编译。
当使用模拟规范的替代方式时,所有警告都会消失:
ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class);
Mockito.doReturn(future).when(executor).schedule(
Mockito.any(Runnable.class),
Mockito.anyLong(),
Mockito.any(TimeUnit.class)
);
在方法级别使用注解。
@SuppressWarnings("unchecked")
我想在调用方法 schedule
时将 ScheduledExecutorService
上的调用模拟为 return 模拟 ScheduledFuture
class。以下代码编译并正常工作:
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
除了我在最后一行收到未经检查的警告:
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
是否有可能以某种方式避免这些警告?
像 ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class);
这样的代码无法编译。
当使用模拟规范的替代方式时,所有警告都会消失:
ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class);
Mockito.doReturn(future).when(executor).schedule(
Mockito.any(Runnable.class),
Mockito.anyLong(),
Mockito.any(TimeUnit.class)
);
在方法级别使用注解。
@SuppressWarnings("unchecked")