天天看點

Mockito 2 關于打标(stubbing)

請參考下面有關于打标的代碼。

//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

https://github.com/cwiki-us-demo/mockito-demo-java/blob/master/src/test/java/com/ossez/demo/mockito/MockitoStubbingTest.java

請注意,上面的測試代碼在運作的時候回出現錯誤。

這是因為在測試代碼運作的時候,我們嘗試輸出 mockedList.get(1),這個在測試的時候,因為我們打标為抛出異常,是以這一句話将會在測試代碼中抛出異常。

運作時候,抛出異常的界面如下:

Mockito 2 關于打标(stubbing)
https://www.cwiki.us/pages/viewpage.action?pageId=47843418