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

求助排查Mockito InvalidUseOfMatchersException异常:匹配器使用问题

Fixing Mockito's InvalidUseOfMatchersException in Your Code

The issue here is a common Mockito pitfall: you’re using argument matchers like any() or anyString() in the thenReturn() method, which violates Mockito’s rules. Matchers are designed exclusively for defining argument expectations in the when() (or verify()) call—not for specifying return values.

Why This Triggers the Error

Mockito tracks matcher usage internally, and using them outside method argument positions (like in thenReturn) messes up the matcher count. This confuses Mockito’s internal logic, leading to the "Invalid use of argument matchers!" error you’re seeing. Return values need to be actual instances, mocks, or literal values—not matchers.

Corrected Code

Here’s how to fix your two mock setup lines:

  1. For the createReq mock:
    Replace the matcher in thenReturn with a real TermReq instance or a mocked version:

    // Option 1: Return a new instance (if TermReq has a no-arg constructor)
    Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(new TermReq());
    
    // Option 2: Return a mocked TermReq (better for complex objects)
    TermReq mockTermReq = Mockito.mock(TermReq.class);
    Mockito.when(service.createReq(Mockito.any(RequestDto.class))).thenReturn(mockTermReq);
    
  2. For the sendPOSTRequest mock:
    Swap the matcher in thenReturn with a concrete string value:

    // Return a dummy response string
    Mockito.when(utils.sendPOSTRequest(Mockito.anyString(), Mockito.anyString())).thenReturn("sample_api_response");
    

Key Takeaway

  • Use argument matchers (any(), anyString(), etc.) only in the method arguments of the mocked method (inside when() or verify()).
  • For return values, provide concrete objects, mocks, or appropriate literal values that match the method’s return type.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 20:37:50