PowerMockito單元測試中的Invalid use of argument matchers問題詳解


首先,簡單說說PowerMockito進行單元測試的三部曲:

打樁,即為非測試目標方法設置返回值,這些返回值在測試目標方法中被使用。
執行測試,調用測試目標方法。
驗證測試結果,如測試方法是否被執行,測試結果是否正確等。
其次,在使用PowerMockito框架進行單元測試的過程中,經常遇到如下異常:

Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at com.mycompany.myproject.mypackage.MyTestClass.myTestMethod(MyTestClass.java:65)
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.
乍一看似乎找不到北,先看看下面的代碼再說。

被測試方法如下:

public boolean toggleOffOn(int delaySeconds) {
boolean off = powerOff();
sleep(delaySeconds);
boolean on = powerOn();
return off && on;
}
測試用例中的測試方法片段如下:

PowerMockito.when(ps.powerOn()).thenReturn(true);
PowerMockito.when(ps.powerOff()).thenReturn(true);
PowerMockito.when(ps.toggleOffOn(Mockito.anyInt())).thenReturn(true);//throws exception here
異常分析:

從異常的位置來看,該異常發生在打樁階段,還未執行到真正的測試。

從異常的信息來看,顯然違反了一個Mockito框架中的Matchers匹配參數的規則。根據Matchers文檔如下,在打樁階段有一個原則,一個mock對象的方法,如果其若干個參數中,有一個是通過Matchers提供的,則該方法的所有參數都必須通過Matchers提供。而不能是有的參數通過Matchers提供,有的參數直接給出真實的具體值。

If you are using argument matchers, all arguments have to be provided by matchers.
E.g: (example shows verification but the same applies to stubbing):

verify(mock).someMethod(anyInt(), anyString(), eq("third argument"));
//above is correct - eq() is also an argument matcher
verify(mock).someMethod(anyInt(), anyString(), "third argument");
//above is incorrect - exception will be thrown because third argument is given without argument matcher.

Matcher methods like anyObject(), eq() do not return matchers. Internally, they record a matcher on a stack and return a dummy value (usually null).
上述文檔中給出的示例,可以使用eq()方法將真實的具體值轉換為Matchers提供的值。

解決方法:

給出具體值
PowerMockito.when(ps.toggleOffOn(3)).thenReturn(true);
或直接去掉(僅適用於該測試用例)
PowerMockito.when(ps.toggleOffOn(Mockito.anyInt())).thenReturn(true);

注意:在Mockito 1.x中,org.mockito.Matchers已經過時,org.mockito.Mockito繼承自Matchers,用以取代Matchers。

 

參考鏈接:

http://static.javadoc.io/org.mockito/mockito-core/1.10.19/org/mockito/Matchers.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM