Mockito 2 參數匹配器
- 2019 年 10 月 6 日
- 筆記
Mockito 通過使用 equals()
這種自然的 Java 樣式來校驗參數值。有時候,當需要有其他一些靈活性的時候,你可能會要求使用參數匹配(argument matchers)。
請參考下面的程式碼:
//stubbing using built-in anyInt() argument matcherwhen(mockedList.get(anyInt())).thenReturn("element"); //stubbing using custom matcher (let's say isValid() returns your own matcher implementation):when(mockedList.contains(argThat(isValid()))).thenReturn("element"); //following prints "element"System.out.println(mockedList.get(999)); //you can also verify using an argument matcherverify(mockedList).get(anyInt()); //argument matchers can also be written as Java 8 Lambdasverify(mockedList).add(argThat(someString -> someString.length() > 5)); |
---|
參數匹配運行進行靈活校驗或者打標。
請訪問 https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/hamcrest/MockitoHamcrest.html 鏈接來查看更多有關自定義參數匹配器/hamcrest matchers(custom argument matchers/hamcrest matchers)的內建參數匹配器和示例。
更多有關 自定義參數匹配器(custom argument matchers)的使用,請參考 ArgumentMatcher
類的 API 文檔。
在使用複雜參數匹配器的時候需要謹慎。嘗試給一個乾淨並且簡單的測試的時候,盡量選擇自然的參數匹配使用的是 equals()
對比相對偶然使用 anyX()
來說。有時候可能對你的程式碼進行一些重構來允許 equals()
進行匹配,或者可以實現(implement)equals()
方法來幫助進行測試。
同時,請閱讀 Capturing arguments for further assertions (Since 1.8.0) 頁面中的內容,或者參考 ArgumentCaptor
類的 API。
ArgumentCaptor
是有關參數匹配器的是特殊實現,能夠為後面的對比(assertions)捕獲參數變數。
參數匹配器的寫法
如果你現在正在使用參數匹配器,所有參數(all arguments)都必須由 matches 提供。
下面的示例程式碼顯示校驗,但是一些將會應用到打標中。
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 an argument matcher. |
---|
像 anyObject()
, eq()
Matcher 方法不會返回 matchers。
在內部,他們將會在堆棧(stack)中記錄一個 matcher 然後返回一個虛假的值(通常為 null)。
這種實現方式是基於 Java 編譯器中有關靜態類型的安全性問題而考慮的,從而帶來的結果是你不能在 verified/stubbed 方法外部使用 anyObject()
, eq()
。
https://www.cwiki.us/display/MockitoZH/Argument+matchers