IT序号网

Java 泛型 : > vs 捕获>

sharpest 2024年11月01日 编程语言 36 0

我正在尝试模拟 ScheduledExecutorService,但我在使用泛型时遇到了麻烦。

这是一个片段:

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

这不会编译并出现以下错误:

Error:(20, 109) java: no suitable method found for  
  thenReturn(java.util.concurrent.ScheduledFuture<capture#1 of ?>) 
method org.mockito.stubbing.OngoingStubbing.thenReturn(java.util.concurrent.ScheduledFuture<capture#2 of ?>) is not applicable 
  (argument mismatch; java.util.concurrent.ScheduledFuture<capture#1 of ?> cannot be converted to java.util.concurrent.ScheduledFuture<capture#2 of ?>) 
method org.mockito.stubbing.OngoingStubbing.thenReturn(java.util.concurrent.ScheduledFuture<capture#2 of ?>,java.util.concurrent.ScheduledFuture<capture#2 of ?>...) is not applicable 
  (argument mismatch; java.util.concurrent.ScheduledFuture<capture#1 of ?> cannot be converted to java.util.concurrent.ScheduledFuture<capture#2 of ?>) 

如果我在声明 ScheduledFuture 时不使用泛型,它会在编译时出现警告。

 ScheduledFuture future  

有什么正确的方法吗?我的意思是,有没有我可以使用的通配符,这样它就可以在没有警告的情况下进行编译?

请您参考如下方法:

以下工作类型正确:

<T> ScheduledFuture<?> thenReturnMockFuture( 
    OngoingStubbing<ScheduledFuture<T>> stubbing) { 
  // Declare a local abstract class, so that future is type-correct. 
  abstract class ScheduledFutureT implements ScheduledFuture<T> {} 
  ScheduledFuture<T> future = mock(ScheduledFutureT.class); 
 
  stubbing.thenReturn(future); 
  return future; 
} 

然后这样调用:

ScheduledExecutorService scheduledExecutorService =  
    mock(ScheduledExecutorService.class); 
 
ScheduledFuture<?> future =  
    thenReturnMockFuture( 
        when(scheduledExecutorService.schedule(...))); 

我想你也可以这样做(没有方法,但有抽象本地类):

ScheduledFuture<?> future = mock(ScheduledFutureT.class); 
doReturn(future).when(scheduledExecutorService).schedule(...); 

注意 the caveatdoReturn不是类型安全的,所以你只需要确保你正在调用一个确实返回 ScheduledFuture<?> 的方法。 .


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!