Unit Test
一般來說,我們應(yīng)該為一個(gè)類中每一個(gè)對(duì)外公開的方法創(chuàng)建單元測(cè)試。書寫單元測(cè)試的一般步驟應(yīng)該是這樣的:
- 創(chuàng)建對(duì)應(yīng)的需要測(cè)試的類的實(shí)例;根據(jù)具體需要測(cè)試的方法來決定是否需要?jiǎng)?chuàng)建實(shí)例對(duì)象,靜態(tài)方法不需要對(duì)應(yīng)實(shí)例,實(shí)例方法則需要。
- 調(diào)用需要測(cè)試的方法;調(diào)用具體的類方法或者是在上一步的實(shí)例對(duì)象上調(diào)用實(shí)例方法。
- 使用Assert語句來斷言。判斷方法的返回值和我們預(yù)期的值是否相等,相等則測(cè)試通過;否則會(huì)拋出AssertionError,測(cè)試失敗。JUnit不會(huì)立即終止執(zhí)行,而是會(huì)統(tǒng)一記錄這些失敗的,等到所有Test Class執(zhí)行完畢后最后給出結(jié)果反饋。
很簡(jiǎn)單,對(duì)吧?Not Exactly?。?!上面的步驟其實(shí)是建立在測(cè)試方法有返回值的情況下的,如果一個(gè)方法僅僅執(zhí)行某些動(dòng)作,并沒有返回值呢?
public class SomeActions {
ActionsImp imp;
public SomeActions(ActionsImp imp) {
this.imp = imp;
}
public void noResultAction(int value){
imp.doSomething(value);
}
}
我們?cè)趺礈y(cè)試SomeActions中的noResultAction方法?因?yàn)闆]有可用的返回值可用來比對(duì),為了測(cè)試這個(gè)方法,我們只能換個(gè)角度去驗(yàn)證imp對(duì)象的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í)就是允許我們模擬需要測(cè)試的類,從而可以驗(yàn)證或者代理這個(gè)Mock類的某些行為??赡鼙容^難理解,直接上代碼說明如何使用mock。這里我們使用Mockito,它是廣泛使用的mock框架之一。
因?yàn)槲覀兓贏ndroid Studio,所以首先需要在build.gradle文件中添加Mockito的依賴:
testCompile 'org.mockito:mockito-core:2.0.73-beta'
要Mock一個(gè)類,首先需要調(diào)用Mockito.mock方法,mock方法有多個(gè)重載版本,但每個(gè)方法都需要指定一個(gè)Class類型參數(shù)用來指代需要mock的類,mock方法的返回值類型為Mock類的類型。使用Mock返回的對(duì)象,我們基本上可以為所欲為了!
//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對(duì)象的某些方法被正確調(diào)用
//using mock object
mockedList.add("one");
mockedList.clear();
//verification
verify(mockedList).add("one");
verify(mockedList).clear();
- 驗(yàn)證mock對(duì)象某些方法的調(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對(duì)象的交互情況
//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對(duì)象的某些方法的行為
```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對(duì)象的帶返回值的方法會(huì)返回默認(rèn)的值,比如返回null、0值或者false等。
- 允許多次代理mock對(duì)象的同一個(gè)方法,但具體的行為取決于該方法最近的一次代理行為。
- mock對(duì)象的代理方法,允許多次調(diào)用,只有不覆蓋它的代理行為,那么每次調(diào)用的執(zhí)行相同的行為或者返回相同的值
- 相同的方法和參數(shù)唯一確認(rèn)一個(gè)代理。比如你可以分別代理get(int)方法在參數(shù)分別為0和1時(shí)的不同行為。
- 代理mock對(duì)象的void方法
doThrow(new RuntimeException()).when(mockedList).clear();
//following throws RuntimeException:
mockedList.clear();
- mock對(duì)象方法的參數(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對(duì)象方法的參數(shù)捕獲
ArgumentCaptor<Person> argument = ArgumentCaptor.forClass(Person.class);
verify(mock).doSomething(argument.capture());
assertEquals("John", argument.getValue().getName());
Mockito還有其他用法,這里就不一一列舉了,請(qǐng)自行參考Mockito類的說明文檔。回到最開始的問題,現(xiàn)在我們可以使用Mockito輕松加愉快的創(chuàng)建對(duì)應(yīng)測(cè)試方法測(cè)試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
請(qǐng)注意,只有事先經(jīng)過mock返回的mock對(duì)象,才能在其上運(yùn)用上面的操作。
先Mock,再使用!
最后,在稍微提一下Mockito的原理!Mock框架一般都是基于Java提供的動(dòng)態(tài)代理或者cglib(code generation lib)。由于Java動(dòng)態(tài)代理僅僅支持接口,在mock一個(gè)具體的類時(shí),mockito使用的是cglib庫來創(chuàng)建動(dòng)態(tài)代理對(duì)象。這里,我們不再深究mockito的實(shí)現(xiàn)原理!