您好,登錄后才能下訂單哦!
Mockito 通過使用?equals()
?這種自然的 Java 樣式來校驗參數(shù)值。有時候,當(dāng)需要有其他一些靈活性的時候,你可能會要求使用參數(shù)匹配(argument matchers)。
請參考下面的代碼:
//stubbing using built-in anyInt() argument matcher when(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 matcher verify(mockedList).get(anyInt()); ? //argument matchers can also be written as Java 8 Lambdas verify(mockedList).add(argThat(someString -> someString.length() >? 5 )); |
參數(shù)匹配運行進(jìn)行靈活校驗或者打標(biāo)。
請訪問?https://static.javadoc.io/org.mockito/mockito-core/3.0.0/org/mockito/hamcrest/MockitoHamcrest.html?鏈接來查看更多有關(guān)自定義參數(shù)匹配器/hamcrest matchers(custom argument matchers/hamcrest matchers)的內(nèi)建參數(shù)匹配器和示例。
更多有關(guān)?自定義參數(shù)匹配器(custom argument matchers)的使用,請參考?ArgumentMatcher
?類的 API 文檔。
在使用復(fù)雜參數(shù)匹配器的時候需要謹(jǐn)慎。嘗試給一個干凈并且簡單的測試的時候,盡量選擇自然的參數(shù)匹配使用的是??equals()
?對比相對偶然使用??anyX()
?來說。有時候可能對你的代碼進(jìn)行一些重構(gòu)來允許??equals()
?進(jìn)行匹配,或者可以實現(xiàn)(implement)equals()
方法來幫助進(jìn)行測試。
同時,請閱讀?Capturing arguments for further assertions (Since 1.8.0)?頁面中的內(nèi)容,或者參考?ArgumentCaptor
?類的 API。
ArgumentCaptor
?是有關(guān)參數(shù)匹配器的是特殊實現(xiàn),能夠為后面的對比(assertions)捕獲參數(shù)變量。
如果你現(xiàn)在正在使用參數(shù)匹配器,所有參數(shù)(all arguments)都必須由 matches 提供。
下面的示例代碼顯示校驗,但是一些將會應(yīng)用到打標(biāo)中。
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。
在內(nèi)部,他們將會在堆棧(stack)中記錄一個?matcher 然后返回一個虛假的值(通常為 null)。
這種實現(xiàn)方式是基于 Java 編譯器中有關(guān)靜態(tài)類型的安全性問題而考慮的,從而帶來的結(jié)果是你不能在?verified/stubbed 方法外部使用?anyObject()
,?eq()
。
?
https://www.cwiki.us/display/MockitoZH/Argument+matchers
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。