單元測試之Mockito

關鍵詞:Mockito

以下內容翻譯整理自:
Mockito latest documentation
[譯] 使用強大的 Mockito 測試框架來測試你的代碼

Unit tests with Mockito - Tutorial
When/how to use Mockito Answer(需要翻墻)
使用Mockito對異步方法進行單元測試

2. 使用mock對象進行測試

單元測試應該盡可能隔離其他類或系統的影響。

  • dummy object
  • Fake objects
  • stub class
  • mock object

可以使用mock框架創建mock對象來模擬類,mock框架允許在運行時創建mock對象,并定義它們的行為。
Mockito是目前流行的mock框架,可以配合JUnit使用。Mockito支持創建和設置mock對象。使用Mockito可以顯著的簡化對那些有外部依賴的類的測試。

  • mock測試代碼中的外部依賴
  • 執行測試
  • 驗證代碼是否執行正確
mockito

4. 使用Mockito API

  • Static imports
    添加static import org.mockito.Mockito.*;

  • Creating and configuring mock objects with Mockito

Mockito支持通過靜態方法mock()創建mock對象,也可以使用@Mock注解。如果使用注解的方式,必須初始化mock對象。使用MockitoRule,調用靜態方法MockitoAnnotations.initMocks(this)初始化標示的屬性字段。

import static org.mockito.Mockito.*;

public class MockitoTest {
    @Mock
    MyDatabase databaseMock;
  
    @Rule
    public MockitoRule mockitoRule = MockitoJUnit.rule();
 
    @Test
    public void testQuery() {
        ClassToTest t = new ClassToTest(databaseMock);
        boolean check = t.query("* from t"); 
        assertTrue(check);
        verify(databaseMock).query("* from t"); 
    }
}
  • Configuring mocks

    • when(…?.).thenReturn(…?.)用于指定條件滿足時的返回值,也可以根據不同的傳入參數返回不同的值。
    • doReturn(…?).when(…?).methodCall作用類似,但是用于返回值為void的函數。
  • Verify the calls on the mock objects
    Mockito會跟蹤mock對象所有的函數調用以及它們的參數,可以用verify()驗證
    一個函數有沒有被調用with指定的參數。這個被稱為"behavior testing"

  • Wrapping Java objects with Spy
    @Spyspy()方法用于封裝實際的對象。除非有特殊聲明(stub),都會真正的調用對象的方法。

  • Using @InjectMocks for dependency injection via Mockito

    • You also have the @InjectMocks annotation which tries to do constructor, method or field dependency injection based on the type.
  • Capturing the arguments
    ArgumentCaptor允許我們在verification期間訪問函數的參數。在捕獲這些函數參數后,可以用于測試。

  • Limitations
    以下不能使用Mockito測試
    • final classes
    • anonymous classes
    • primitive types
1. Mockito Answer的使用

A common usage of Answer is to stub asynchronous methods that have callbacks.

doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
    Callback callback = (Callback) invocation.getArguments()[0];
    callback.onSuccess(cannedData);
    return null;
    }
}).when(service).get(any(Callback.class));

Answer can also be used to make smarter stubs for synchronous methods.

when(translator.translate(any(String.class))).thenAnswer(reverseMsg())
...
// extracted a method to put a descriptive name
private static Answer<String> reverseMsg() {
    return new Answer<String>() {
        public String answer(InvocationOnMock invocation) {
            return reverseString((String) invocation.getArguments()[0]));
        }
    }
}

Mockito限制

  • final classes
  • anonymous classes
  • primitive types

Mockito示例

1. Let's verify some behaviour!
//Let's import Mockito statically so that the code looks clearer 
import static org.mockito.Mockito.*; 

//mock creation 
List mockedList = mock(List.class); 

//using mock object 
mockedList.add("one"); 
mockedList.clear(); 

//verification 
verify(mockedList).add("one"); 
verify(mockedList).clear();

驗證某些操作是否執行

Once created, a mock will remember all interactions. Then you can selectively verify whatever interactions you are interested in.

2. How about some 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. Not convinced? See [here](http://monkeyisland.pl/2008/04/26/asking-and-telling). 
verify(mockedList).get(0);

By default, for all methods that return a value, a mock will return either null, a a primitive/primitive wrapper value, or an empty collection, as appropriate. For example 0 for an int/Integer and false for a boolean/Boolean.

3. 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(someString -> someString.length() > 5);

If you are using argument matchers, all arguments have to be provided by matchers.

5. Stubbing void methods with exceptions
doThrow(new RuntimeException()).when(mockedList).clear(); 

//following throws RuntimeException: 
mockedList.clear();
6. Verification in order
// A. Single mock whose methods must be invoked in a particular order 
List singleMock = mock(List.class); 

//using a single mock 
singleMock.add("was added first"); 
singleMock.add("was added second"); 

//create an inOrder verifier for a single mock 
InOrder inOrder = inOrder(singleMock); 

//following will make sure that add is first called with "was added first, then with "was added second" 
inOrder.verify(singleMock).add("was added first"); 
inOrder.verify(singleMock).add("was added second"); 

// B. Multiple mocks that must be used in a particular order 
List firstMock = mock(List.class); 
List secondMock = mock(List.class); 

//using mocks 
firstMock.add("was called first"); 
secondMock.add("was called second"); 

//create inOrder object passing any mocks that need to be verified in order 
InOrder inOrder = inOrder(firstMock, secondMock); 

//following will make sure that firstMock was called before secondMock 
inOrder.verify(firstMock).add("was called first"); 
inOrder.verify(secondMock).add("was called second"); 

// Oh, and A + B can be mixed together at will
7. Making sure interaction(s) never happened on mock
//using mocks - only mockOne is interacted 
mockOne.add("one"); 

//ordinary verification 
verify(mockOne).add("one"); 

//verify that method was never called on a mock 
verify(mockOne, never()).add("two"); 

//verify that other mocks were not interacted 
verifyZeroInteractions(mockTwo, mockThree);
8. Finding redundant invocations
//using mocks 
mockedList.add("one"); 
mockedList.add("two"); 

verify(mockedList).add("one"); 

//following verification will fail 
verifyNoMoreInteractions(mockedList);

verifyNoMoreInteractions() is a handy assertion from the interaction testing toolkit. Use it only when it's relevant. Abusing it leads to overspecified, less maintainable tests.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,533評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,055評論 3 414
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,365評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,561評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,346評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,889評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,978評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,118評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,637評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,558評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,739評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,246評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,980評論 3 346
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,362評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,619評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,347評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,702評論 2 370

推薦閱讀更多精彩內容

  • 在博客Android單元測試之JUnit4中,我們簡單地介紹了:什么是單元測試,為什么要用單元測試,并展示了一個簡...
    水木飛雪閱讀 9,506評論 4 18
  • 背景 在寫單元測試的過程中,一個很普遍的問題是,要測試的目標類會有很多依賴,這些依賴的類/對象/資源又會有別的依賴...
    johnnycmj閱讀 1,180評論 0 3
  • 什么是Mock? 在單元測試中,我們往往想去獨立地去測一個類中的某個方法,但是這個類可不是獨立的,它會去調用一些其...
    健談的Boris閱讀 22,902評論 0 14
  • 什么是 Mock mock 的中文譯為: 仿制的,模擬的,虛假的。對于測試框架來說,即構造出一個模擬/虛假的對象,...
    Whyn閱讀 4,368評論 0 3
  • 寫在前面 因個人能力有限,可能會出現理解錯誤的地方,歡迎指正和交流! 關于單元測試 通常一個優秀的開源框架,一般都...
    汪海游龍閱讀 2,913評論 0 21