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

为何Groovy下使用Mockito 3.12 mock RestTemplate的exchange方法返回空触发NPE

错误原因
  • 括号嵌套语法错误:现有mock代码中any(HttpMethod.class未闭合右括号,将后续HttpEntity、Class类型的匹配器错误传入any(HttpMethod.class)作为参数,导致Mockito无法识别匹配规则,mock不生效返回null。
  • 入参类型不匹配:目标方法调用的第四个入参为AnimalVO.class(属于Class类型),但现有匹配器写为any(ValueObject.class) as Class,类型不符无法命中方法调用。
  • 可变参数缺失匹配:exchange方法签名最后一个参数为可变参数Object... uriVariables,即使调用时未传参(等效传入空数组),也需要补充匹配规则才能正确命中。
修复后的代码示例
// 通用匹配写法,适配所有同参数数量的exchange调用
when(restTemplate.exchange(
    anyString(),
    any(HttpMethod.class),
    any(HttpEntity.class),
    any(Class.class),
    any()
)).thenReturn(responseEntityMocked)

// 精确匹配写法,仅命中GET请求、返回类型为AnimalVO的调用
when(restTemplate.exchange(
    anyString(),
    eq(HttpMethod.GET),
    any(HttpEntity.class),
    eq(AnimalVO.class),
    any()
)).thenReturn(responseEntityMocked)
补充说明
  • 所有参数匹配规则必须统一:要么全部使用匹配器(any/eq等),要么全部使用精确值,不可混合使用,否则会导致匹配失败。
  • Groovy环境下建议引入mockito-groovy依赖,避免Groovy语法特性导致的Mockito匹配异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 04:09:03