繁体   English   中英

Mockito-InvalidUseOfMatchersException

[英]Mockito - InvalidUseOfMatchersException

我已经尝试调试这段代码了一段时间,但还是没有运气。 我继续为此代码专门抛出“ InvalidUseOfMatchersException”:

对于设置:

        service = mock(Service.class);
        newRequest = mock(Request.class);
        when(service.newRequest(anyString(), anyString(), anyString())).thenReturn(
            newRequest);

在该服务使用的类中:

 Request newRequest = Service.newRequest(
            mId, "mp", itemID);

我假设它失败了,因为我在when ... thenReturn子句中传入了3个“ anyString()”,但可能是在硬编码的“ mp”上失败了。 所以我试图用以下内容替换when子句:

when(service.newRequest(anyString(), eq("mp"), anyString())).thenReturn(
            newRequest);

但是仍然会收到InvalidUseOfMatchersException。

我是否缺少有关模仿的工作方式的信息?

全栈:

    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)

基于以下语法:

Service.newRequest(mId, "mp", itemID);

看起来newRequest是静态方法。 Mockito本质上是通过子类化(实际上生成动态代理)来工作的,因此它不适用于静态方法,因为无法通过子类覆盖静态方法。 由于类似的原因,最终方法不可模仿。

如果正确,请切换到工厂对象而不是工厂方法,这将使您模拟工厂实例,或使用Powermock模拟静态字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM