求助排查Mockito InvalidUseOfMatchersException异常:匹配器使用问题
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:
For the
createReqmock:
Replace the matcher inthenReturnwith a realTermReqinstance 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);For the
sendPOSTRequestmock:
Swap the matcher inthenReturnwith 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 (insidewhen()orverify()). - For return values, provide concrete objects, mocks, or appropriate literal values that match the method’s return type.
内容的提问来源于stack exchange,提问作者Manish

