【问题标题】:Avoiding unchecked warnings when using Mockito使用 Mockito 时避免未经检查的警告
【发布时间】:2015-12-26 20:33:04
【问题描述】:

我想模拟对 ScheduledExecutorService 的调用,以在调用方法 schedule 时返回 ScheduledFuture 类的模拟。以下代码编译并正常工作:

    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&lt;?&gt; future = Mockito.mock(ScheduledFuture.class); 之类的代码无法编译。

【问题讨论】:

  • 您的ScheduledFuture 打算在您的实际代码中绑定到什么类型?
  • 我是ScheduledFuture&lt;?&gt;,因为我只提交Runnable
  • 如果这个特定的测试功能正常,我不会太担心。如果它的类型绑定到Object,可能有一种方法可以删除警告,但我怀疑这是否值得改变。您能否粘贴特定的测试和测试代码,以便我们可以在自己的环境中复制它?复制警告就够了。
  • @Makoto 我已经用模拟声明更新了测试,我认为它应该足以复制。我在这里不能有警告,因为我正在禁止所有编译器警告的环境中编译项目。
  • 嗯...那很不幸。好吧,我看到了困境。

标签: java mockito unchecked


【解决方案1】:

当使用替代的模拟规范方式时,所有警告都会消失:

    ScheduledFuture<?> future = Mockito.mock(ScheduledFuture.class);
    Mockito.doReturn(future).when(executor).schedule(
        Mockito.any(Runnable.class),
        Mockito.anyLong(),
        Mockito.any(TimeUnit.class)
    );

【讨论】:

    【解决方案2】:

    在方法级别使用注解。

    @SuppressWarnings("unchecked")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-04
      • 2012-03-18
      • 1970-01-01
      • 1970-01-01
      • 2015-05-03
      • 2020-02-03
      • 2015-05-02
      • 1970-01-01
      相关资源
      最近更新 更多