請參考下面有關於打標的代碼。
//You can mock concrete classes, not just interfaces LinkedList mockedList = mock(LinkedList. class ); //stubbing when(mockedList.get( 0 )).thenReturn( "first" ); when(mockedList.get( 1 )).thenThrow( new RuntimeException()); //following prints "first" System.out.println(mockedList.get( 0 )); //following throws runtime exception System.out.println(mockedList.get( 1 )); //following prints "null" because get(999) was not stubbed System.out.println(mockedList.get( 999 )); //Although it is possible to verify a stubbed invocation, usually it's just redundant //If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed). //If your code doesn't care what get(0) returns, then it should not be stubbed. verify(mockedList).get( 0 ); |
在默認情況下,所有的方法都會有一個返回值。mock 函數默認返回的是 null,一個空的集合或者一個被對象類型包裝的內置類型。例如,針對 int/Integer 將會返回 0,針對 boolean/Boolean 將會返回 false。
打標(Stubbing)可以被重寫:例如一個通用的打標可以在啓動的時候被確定(fixture),但是測試方法可以對其進行重寫(override)。請注意重寫的打標可能會在有很多標記的時候存在潛在的問題。
一旦被打標,方法將會總是返回已標記的內容,這個與這個方法被調用多少次無關。
最後的標記非常重要——當你對有相同參數的方法進行多次標記的時候。換句話說就是:標記的順序是有關的(the order of stubbing matters),但是這個意義並不是很大。例如,這個只在標記完全相同的方法或者有時候參數匹配(argument matchers)被啓用的時候,等情況下才會出現。, etc.
測試代碼請訪問 GitHub
請注意,上面的測試代碼在運行的時候回出現錯誤。
這是因爲在測試代碼運行的時候,我們嘗試輸出 mockedList.get(1),這個在測試的時候,因爲我們打標爲拋出異常,所以這一句話將會在測試代碼中拋出異常。
運行時候,拋出異常的界面如下:
https://www.cwiki.us/pages/viewpage.action?pageId=47843418