[英]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.