Unit Test
一般來說顷级,我們應(yīng)該為一個類中每一個對外公開的方法創(chuàng)建單元測試鳞陨。書寫單元測試的一般步驟應(yīng)該是這樣的:
- 創(chuàng)建對應(yīng)的需要測試的類的實(shí)例帚戳;根據(jù)具體需要測試的方法來決定是否需要創(chuàng)建實(shí)例對象棵帽,靜態(tài)方法不需要對應(yīng)實(shí)例妹卿,實(shí)例方法則需要旺矾。
- 調(diào)用需要測試的方法蔑鹦;調(diào)用具體的類方法或者是在上一步的實(shí)例對象上調(diào)用實(shí)例方法。
- 使用Assert語句來斷言箕宙。判斷方法的返回值和我們預(yù)期的值是否相等嚎朽,相等則測試通過;否則會拋出AssertionError柬帕,測試失敗哟忍。JUnit不會立即終止執(zhí)行,而是會統(tǒng)一記錄這些失敗的陷寝,等到所有Test Class執(zhí)行完畢后最后給出結(jié)果反饋锅很。
很簡單,對吧凤跑?Not Exactly1病!仔引!上面的步驟其實(shí)是建立在測試方法有返回值的情況下的扔仓,如果一個方法僅僅執(zhí)行某些動作,并沒有返回值呢咖耘?
public class SomeActions {
ActionsImp imp;
public SomeActions(ActionsImp imp) {
this.imp = imp;
}
public void noResultAction(int value){
imp.doSomething(value);
}
}
我們怎么測試SomeActions
中的noResultAction
方法翘簇?因?yàn)闆]有可用的返回值可用來比對,為了測試這個方法儿倒,我們只能換個角度去驗(yàn)證imp
對象的doSomething
方法被調(diào)用版保,且調(diào)用參數(shù)為value值。Oh义桂,No找筝!How To Do?別擔(dān)心慷吊,一切的一切袖裕,使用Mock
框架就行!
What is Mock & How to Use
到底什么是Mock呢溉瓶?Mock的英文解釋是模擬急鳄、偽造。廢話不多說堰酿,Mock框架其實(shí)就是允許我們模擬需要測試的類疾宏,從而可以驗(yàn)證或者代理這個Mock類的某些行為〈ゴ矗可能比較難理解坎藐,直接上代碼說明如何使用mock。這里我們使用Mockito,它是廣泛使用的mock框架之一岩馍。
因?yàn)槲覀兓贏ndroid Studio碉咆,所以首先需要在build.gradle文件中添加Mockito的依賴:
testCompile 'org.mockito:mockito-core:2.0.73-beta'
要Mock一個類,首先需要調(diào)用Mockito.mock方法蛀恩,mock方法有多個重載版本疫铜,但每個方法都需要指定一個Class類型參數(shù)用來指代需要mock的類,mock方法的返回值類型為Mock類的類型双谆。使用Mock返回的對象壳咕,我們基本上可以為所欲為了!
//Let's import Mockito statically so that the code looks clearer
import static org.mockito.Mockito.*;
//mock creation
List mockedList = mock(List.class);
- 驗(yàn)證mock對象的某些方法被正確調(diào)用
//using mock object
mockedList.add("one");
mockedList.clear();
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
- 驗(yàn)證mock對象某些方法的調(diào)用次數(shù)
```java
//using mock
mockedList.add("once");
mockedList.add("twice");
mockedList.add("twice");
mockedList.add("three times");
mockedList.add("three times");
mockedList.add("three times");
//following two verifications work exactly the same - times(1) is used by default
verify(mockedList).add("once");
verify(mockedList, times(1)).add("once");
//exact number of invocations verification
verify(mockedList, times(2)).add("twice");
verify(mockedList, times(3)).add("three times");
//verification using never(). never() is an alias to times(0)
verify(mockedList, never()).add("never happened");
//verification using atLeast()/atMost()
verify(mockedList, atLeastOnce()).add("three times");
verify(mockedList, atLeast(2)).add("five times");
verify(mockedList, atMost(5)).add("three times");
- 驗(yàn)證和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);
//using mocks
mockedList.add("one");
mockedList.add("two");
verify(mockedList).add("one");
//following verification will fail
verifyNoMoreInteractions(mockedList);
- 代理mock對象的某些方法的行為
```java
//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.
verify(mockedList).get(0);
- 默認(rèn)情況下顽馋,調(diào)用mock對象的帶返回值的方法會返回默認(rèn)的值谓厘,比如返回null、0值或者false等趣避。
- 允許多次代理mock對象的同一個方法庞呕,但具體的行為取決于該方法最近的一次代理行為新翎。
- mock對象的代理方法程帕,允許多次調(diào)用,只有不覆蓋它的代理行為地啰,那么每次調(diào)用的執(zhí)行相同的行為或者返回相同的值
- 相同的方法和參數(shù)唯一確認(rèn)一個代理愁拭。比如你可以分別代理get(int)方法在參數(shù)分別為0和1時(shí)的不同行為。
- 代理mock對象的void方法
doThrow(new RuntimeException()).when(mockedList).clear();
//following throws RuntimeException:
mockedList.clear();
- mock對象方法的參數(shù)匹配
//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(true);
//following prints "element"
System.out.println(mockedList.get(999));
//**you can also verify using an argument matcher**
verify(mockedList).get(anyInt());
- mock對象方法的參數(shù)捕獲
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
Mockito還有其他用法亏吝,這里就不一一列舉了岭埠,請自行參考Mockito類的說明文檔∥蹬福回到最開始的問題惜论,現(xiàn)在我們可以使用Mockito輕松加愉快的創(chuàng)建對應(yīng)測試方法測試noResultAction
方法了。如下:
@Test
public void testNoResultAction() throws Exception {
ActionsImp mock = Mockito.mock(ActionsImp.class);
SomeActions someActions = new SomeActions(mock);
someActions.noResultAction(5);
Mockito.verify(mock).doSomething(5);
}
Othes
請注意止喷,只有事先經(jīng)過mock返回的mock對象馆类,才能在其上運(yùn)用上面的操作。
先Mock弹谁,再使用乾巧!
最后,在稍微提一下Mockito的原理预愤!Mock框架一般都是基于Java提供的動態(tài)代理或者cglib(code generation lib)沟于。由于Java動態(tài)代理僅僅支持接口,在mock一個具體的類時(shí)植康,mockito使用的是cglib庫來創(chuàng)建動態(tài)代理對象旷太。這里,我們不再深究mockito的實(shí)現(xiàn)原理销睁!