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

Mockito中InvalidUseOfMatchersException异常求助:参数匹配器使用错误

Fixing Mockito's InvalidUseOfMatchersException in Your Test Code

Hey there! I’ve run into this exact Mockito issue before—let’s break down what’s going wrong and how to fix it quickly.

What’s Causing the Error?

The exception org.mockito.exceptions.misusing.InvalidUseOfMatchersException is thrown because you’re mixing argument matchers (like any()) with real object instances in the same method call when stubbing. Mockito has a strict rule here:

Either all arguments are matchers, or none are. You can’t use a matcher for one parameter and a real object for another.

In your code, you’re using any() for the first parameter but passing the real context instance for the second—this violates the rule, hence the error saying "2 matchers expected, 1 recorded".

Two Simple Fixes

1. Use a Matcher for the Second Parameter

Wrap your context instance with Mockito’s eq() matcher, which tells Mockito to match exactly that specific object. This makes both parameters use matchers, which is allowed:

@Mock private Context context;
// ...
when(service.getResult(any(), eq(context))).thenReturn(new ArrayList<>());

eq() is perfect here because it checks for object equality with your real context instance while still counting as a valid matcher.

2. Use Real Values for Both Parameters

If you don’t need the flexibility of a matcher for the first parameter, just pass a real object instead of any(). This way, both parameters are real instances, which also complies with Mockito’s rules:

@Mock private Context context;
// Replace actualFirstParam with your real first argument value
when(service.getResult(actualFirstParam, context)).thenReturn(new ArrayList<>());

Quick Note

Remember: Mockito matchers (like any(), eq(), isNull()) only work in the context of stubbing (when()) or verifying (verify()) method calls. Don’t use them elsewhere in your test code—they’ll cause unexpected behavior!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:14:23