java - 使用 Mockito 时避免未经检查的警告

标签 java mockito unchecked

我想在 ScheduledExecutorService 上模拟一个电话返回 ScheduledFuture 的模拟类时方法 schedule被调用。以下代码编译并正常工作:

    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)
    );

关于java - 使用 Mockito 时避免未经检查的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475010/

相关文章:

java - org.hibernate.hql.internal.QueryExecutionRequestException : Not supported for DML operations without using hibernate

java - mockito 中的部分模拟 - 强制方法进入异常并继续

flutter - 如何模拟导航参数以测试 flutter 屏幕小部件?

java - 具有自定义用户的 SpringBootTest 模拟身份验证主体不起作用

java - "throws UncheckedException"是否有意义

java - 如何在外部添加.so文件

java - Android 查找联系人时出错

"indexed"属性文件的 Java API

java - 数组队列 - 使用 -xlint : unchecked/unsafe operations 重新编译

java - 泛型和类转换