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

Mockito如何捕获方法的Class<T>类型参数?

问题描述

泛型方法定义

public <T> T response(RequestContent requestContent, Class<T> returnType) throws Exception
{
  var response = getResponse(requestContent);
  var type = objectMapper.getTypeFactory().constructType(returnType);
  return objectMapper.readValue(response, type);
}

实际调用示例

var res = response(requestContent, Account.class);

Mockito使用困惑

  1. 使用doReturnStub方法时,不知道第二个参数该如何匹配:
doReturn(Account).when(stub).response(isA(RequestContent.class), ???);
  1. 使用ArgumentCaptor捕获参数时,第二个参数的处理方式不明确:
verify(stub).getResponseClass(requestCaptor.capture(), ???);

运行时错误提示

No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()


解决方案

一、正确使用doReturn进行Stub

  1. 修正返回值:doReturn(Account)是错误写法,需要传入Account的实例而非类本身,比如用默认构造函数创建实例:new Account()。
  2. 匹配第二个参数:针对Class<T>类型参数,可用两种匹配方式:
    • 精确匹配:eq(Account.class),只匹配传入Account.class的情况;
    • 模糊匹配:any(Class.class),匹配任意Class类型参数。

正确代码示例:

// 精确匹配Account.class作为第二个参数
doReturn(new Account()).when(stub).response(isA(RequestContent.class), eq(Account.class));

// 匹配任意Class类型参数
doReturn(new Account()).when(stub).response(isA(RequestContent.class), any(Class.class));

二、正确使用ArgumentCaptor捕获参数

步骤说明:

  1. 先定义对应类型的参数捕获器:
ArgumentCaptor<RequestContent> requestCaptor = ArgumentCaptor.forClass(RequestContent.class);
  1. 在verify中使用捕获器,第二个参数用匹配器匹配:
// 精确匹配Account.class,确保只捕获对应调用的参数
verify(stub).response(requestCaptor.capture(), eq(Account.class));

// 匹配任意Class类型,捕获所有符合第一个参数类型的调用
verify(stub).response(requestCaptor.capture(), any(Class.class));
  1. 获取并验证捕获到的参数:
RequestContent capturedRequest = requestCaptor.getValue();
// 此处可对capturedRequest进行断言验证,比如检查属性值

三、错误原因及修复

出现No argument value was captured!的常见原因:

  • verify中的参数匹配器和实际调用的参数不匹配,导致方法调用未被识别,捕获器无数据;
  • 在Stub操作(比如doReturn)中使用了capture(),Mockito推荐仅在verify中使用捕获器;
  • 被verify的方法实际并未被调用。

修复要点:

  • 保证verify的参数匹配器和实际调用完全对应;
  • 仅在verify阶段使用ArgumentCaptor.capture();
  • 确认待验证的方法确实被执行过。

内容的提问来源于stack exchange,提问作者Karos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 14:52:45