You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mockito测试异步任务中Transport.send方法遇类型匹配错误求助

解决Mockito中ExecutorService.submit返回Future<?>的类型匹配问题

问题原因

ExecutorService的submit(Runnable)方法返回类型是Future<?>,由于Java泛型的通配符捕获机制,Mockito在生成Stubbing逻辑时,会将返回值的通配符捕获为两个不同的匿名类型(CAP#1和CAP#2),导致你mock的Future<?>对象无法与Stubbing期望的类型匹配,触发编译错误。

可行解决方案

1. 显式指定Mockito泛型类型

在when调用前明确指定泛型为Future<?>,强制类型匹配:

Mockito.<Future<?>>when(mockExecutor.submit(any(Runnable.class))).thenReturn(mockFuture);

2. 改用doReturn语法绕过类型推断

doReturn语法不依赖于方法调用的返回值类型推断,能直接绕过泛型匹配问题:

doReturn(mockFuture).when(mockExecutor).submit(any(Runnable.class));

3. 确保mock对象的类型正确

定义mock Future时,明确指定为Future<?>(如果之前没这么做):

Future<?> mockFuture = mock(Future.class);

内容的提问来源于stack exchange,提问作者Bhavya Sai Kamasamudram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 16:02:37