單元測試之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.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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