Mockito

Mockito是一個Java平台的開源單元測試框架列表，在MIT許可證下發布。該框架允許在自動化單元測試中創建測試替身對象（模擬對象），用於測試驅動開發（TDD）或行為驅動開發（BDD）。

該框架的名稱和圖標是對莫吉托（Mojito，一種飲料）的模仿。

## 特點

Mockito允許開發人員驗證被測系統（SUT）的行為，而無需事先建立期望。對於模擬對象，有人批評其測試代碼與被測系統的緊耦合。Mockito試圖通過取消期望規範，來擺脫「期望-運行-驗證」的模式。Mockito還提供了一些用於減少樣板代碼的註解。

## 起源

Mockito是從擴展EasyMock的語法和功能開始的。

## 例子

下面是一個非耦合的Hello world程序；我們可以對它的某些部分進行單元測試，對其它部分使用模擬對象。

```java
package org.examples;

import java.io.IOException;

public class HelloApplication {

   public static interface Greeter {
      String getGreeting(String subject);
      String getIntroduction(String actor);
   }
   
   public static class HelloGreeter implements Greeter {
      private String hello;
      private String segmenter;
      
      public HelloGreeter(String hello, String segmenter) {
         this.hello = hello;
         this.segmenter = segmenter;
      }
      public String getGreeting(String subject) {
         return hello + " " + subject; 
      }
      public String getIntroduction(String actor) {
         return actor+segmenter;
      }
   }
   
   public static interface HelloActable {
      void sayHello(String actor, String subject) throws IOException;
   }
   
   public static class HelloAction implements HelloActable {
      private Greeter helloGreeter;
      private Appendable helloWriter;

      public HelloAction(Greeter helloGreeter, Appendable helloWriter) {
         super();
         this.helloGreeter = helloGreeter;
         this.helloWriter = helloWriter;
      }
      public void sayHello(String actor, String subject) throws IOException { 
         helloWriter.append(helloGreeter.getIntroduction(actor)).append(helloGreeter.getGreeting(subject));
      }
   }

   public static void main(String... args) throws IOException {
      new HelloAction(new HelloGreeter("hello", ": "), System.out).sayHello("application", "world");
   }

}
```

啟動HelloApplication後，結果如下：

```
application: hello world
```

HelloActable組件的單元測試可能如下：

```java
package org.examples;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import org.examples.HelloApplication.HelloActable;
import org.examples.HelloApplication.HelloAction;
import org.examples.HelloApplication.Greeter;

public class HelloActionUnitTest {
   
   Greeter helloGreeterMock;
   Appendable helloWriterMock;
   HelloActable helloAction;
   
   @Before
   public void setUp() {
      helloGreeterMock = mock(Greeter.class);
      helloWriterMock = mock(Appendable.class);
      helloAction = new HelloAction(helloGreeterMock, helloWriterMock);
   }
   
   @Test
   public void testSayHello() throws Exception {
      when(helloWriterMock.append(any(String.class))).thenReturn(helloWriterMock);
      when(helloGreeterMock.getIntroduction(eq("unitTest"))).thenReturn("unitTest : ");
      when(helloGreeterMock.getGreeting(eq("world"))).thenReturn("hi world");
      
      helloAction.sayHello("unitTest", "world");
      
      verify(helloGreeterMock).getIntroduction(eq("unitTest"));
      verify(helloGreeterMock).getGreeting(eq("world"));

      verify(helloWriterMock, times(2)).append(any(String.class));
      verify(helloWriterMock, times(1)).append(eq("unitTest : "));
      verify(helloWriterMock, times(1)).append(eq("hi world"));
   }
}
```

它為Greeter和Appendable接口使用了模擬對象，並隱式假設了下一個用例：

```
unitTest : hi world
```

用於測試Greeter與HelloActable聯合在一起的集成測試代碼可能如下：

```java
package org.examples;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import org.junit.Before;
import org.junit.Test;

import org.examples.HelloApplication.HelloActable;
import org.examples.HelloApplication.HelloAction;
import org.examples.HelloApplication.Greeter;
import org.examples.HelloApplication.HelloGreeter;

public class HelloActionIntegrationTest {
   HelloActable helloAction;
   Greeter helloGreeter;
   Appendable helloWriterMock;
   
   @Before
   public void setUp() {
      helloGreeter = new HelloGreeter("welcome", " says ");
      helloWriterMock = mock(Appendable.class);
      helloAction = new HelloAction(helloGreeter, helloWriterMock);
   }
   
   @Test
   public void testSayHello() throws Exception {
      when(helloWriterMock.append(any(String.class))).thenReturn(helloWriterMock);

      helloAction.sayHello("integrationTest", "universe");

      verify(helloWriterMock, times(2)).append(any(String.class));
      verify(helloWriterMock, times(1)).append(eq("integrationTest says "));
      verify(helloWriterMock, times(1)).append(eq("welcome universe"));
   }
}
```

它僅使用模擬對象代替Appendable接口，而使用其它（HelloActable和Greeter）接口的真實實現，並隱式假設了下一個用例：

```
integrationTest says welcome universe
```

從HelloActionUnitTest和HelloActionIntegrationTest這兩個類的import語句可以看出，需要在類路徑中加入一些Mockito和JUnit的包才能編譯和運行測試類。

## 基本資料

- 開發者：史蒂芬·費伯（Szczepan Faber）、布萊斯·杜泰爾（Brice Dutheil）、拉斐爾·溫特哈特（Rafael Winterhalter）、蒂姆·范德利普（Tim van der Lippe）等
- 程式語言：Java
- 類型：測試
- 許可協議：MIT許可證