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

Mockito严格存根参数不匹配错误排查与代码修复请求

问题原因与修复方案

错误原因

  1. 参数匹配器使用违规:存根时List.of(anyInt())的写法不符合Mockito规则——参数匹配器(如anyInt())不能直接嵌套在容器(比如List.of())内部,这会导致存根的参数是一个包含匹配器占位符的List,和实际调用传入的List.of(0)无法匹配。
  2. Verify阶段实例不统一:verify时调用mock(Pageable.class)生成了全新的Pageable实例,和实际调用时传入的Pageable对象不是同一个实例,触发Strict stubbing的参数不匹配校验。

修复后的测试代码

@Test
public void getCoopPipelineOutlinesWithFilter_returnsExpectedResult() {
    PagedResult<PipelineItem> expected = mock(PagedResult.class);
    // 使用eq()匹配具体List,或用anyList()匹配任意List
    when(aggregateService.getCoopPipelineItems(eq(List.of(0)), anyString(), anyString(), any(Pageable.class)))
        .thenReturn(expected);

    List<Integer> orgIds = List.of(0);
    Pageable pageable = mock(Pageable.class); // 提前创建实例,保证调用与verify复用同一个
    PagedResult<PipelineItem> result = controller.getCoopPipelineOutlinesWithFilter(orgIds, "submitted", "filter", pageable);

    Assertions.assertEquals(expected, result);
    // verify时使用提前创建的pageable实例,而非新mock
    verify(aggregateService).getCoopPipelineItems(orgIds, "submitted", "filter", pageable);
}

补充说明

  • 如果不需要严格校验orgIds的具体值,也可以用anyList()替代eq(List.of(0)),让存根逻辑更灵活:
    when(aggregateService.getCoopPipelineItems(anyList(), anyString(), anyString(), any(Pageable.class)))
        .thenReturn(expected);
    
  • Mockito默认开启的Strict stubbing模式会严格校验存根参数与实际调用参数的匹配度,避免存根被误用,因此必须保证存根、实际调用、verify三个环节的参数完全匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 13:17:04