[英]Mockito - InvalidUseOfMatchersException
I have been trying to debug this piece of code for a while now but still no luck. 我已经尝试调试这段代码了一段时间,但还是没有运气。 I continues to throw "InvalidUseOfMatchersException" specifically for this code:
我继续为此代码专门抛出“ InvalidUseOfMatchersException”:
For the set up: 对于设置:
service = mock(Service.class);
newRequest = mock(Request.class);
when(service.newRequest(anyString(), anyString(), anyString())).thenReturn(
newRequest);
And in the class that service is used in: 在该服务使用的类中:
Request newRequest = Service.newRequest(
mId, "mp", itemID);
I am assuming that it fails because I pass in 3 "anyString()" in the when...thenReturn clause but it could possibly be that it is failing on the hardcoded "mp". 我假设它失败了,因为我在when ... thenReturn子句中传入了3个“ anyString()”,但可能是在硬编码的“ mp”上失败了。 So I tried to replace the when clause with this:
所以我试图用以下内容替换when子句:
when(service.newRequest(anyString(), eq("mp"), anyString())).thenReturn(
newRequest);
But still receive the InvalidUseOfMatchersException. 但是仍然会收到InvalidUseOfMatchersException。
Am I missing something about how mockito is supposed to work for this? 我是否缺少有关模仿的工作方式的信息?
full stack: 全栈:
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
3 matchers expected, 2 recorded.
This exception may occur if matchers are combined with raw values:
//incorrect:
someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
//correct:
someMethod(anyObject(), eq("String by matcher"));
For more info see javadoc for Matchers class.
at ServiceFacade.getSimilarities(ServiceFacade.java:29)
at FacadeTest.getSimilarities(FacadeTest.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodImpl.invoke(DelegatingMethodImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
Based on this syntax: 基于以下语法:
Service.newRequest(mId, "mp", itemID);
It looks like newRequest
is a static method. 看起来
newRequest
是静态方法。 Mockito inherently works by subclassing (actually generating dynamic proxies), so it doesn't work on static methods because the static method can't be overridden through subclassing. Mockito本质上是通过子类化(实际上生成动态代理)来工作的,因此它不适用于静态方法,因为无法通过子类覆盖静态方法。 Final methods aren't mockable for similar reasons.
由于类似的原因,最终方法不可模仿。
If that's correct, switch to a factory object instead of factory method, which will let you mock the instance of the factory, or use Powermock to mock static fields. 如果正确,请切换到工厂对象而不是工厂方法,这将使您模拟工厂实例,或使用Powermock模拟静态字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.