対象

Mockito 1.8.0

Mockitoとは

タイプセーフなJavaのモック生成フレームワーク
JUnitと組み合わせてユニットテストを効率化する

準備

Mockitoのstaticメンバをstaticインポートしておく
 import static org.mockito.Mockito.*;


使い方

モックの作成(HttpServletRequestの場合)

HttpServletRequest request = mock(HttpServletRequest.class);

モックの振る舞いを操作する

戻り値を操作する
 when(request.getSession()).thenReturn(new HttpSession());
 when(request.getAttribuete("キー").thenThrow(new RuntimeException());
voidメソッドが投げる例外を操作する
 doThrow(new RuntimeException()).when(request).getAttribuete("キー");
任意のメソッドを実行した結果を戻り値として返す
// ※anyString()は任意の文字列という意味
when(request.getParameter(anyString())).thenAnswer(new Answer<String>() {
   public String answer(InvocationOnMock invocation) throws Throwable {
      String key = (String) invocation.getArguments()[0];
      return key + "の値";
   }
});

モックの任意のメソッドが呼ばれたかを確認する

 verify(request).getAttribute("キー");
複数回呼ばれる可能性がある場合に、最低1回は呼ばれる事を確認する
 verify(request, Mockito.atLeastOnce()).getAttribute("キー");
呼ばれた順番を確認する
 InOrder order = inOrder(request, オブジェクト2, オブジェクト3,...);
 order.verify(request).getAttribute("key1");
 order.verify(request).getAttribute("key2");
 order.verify(オブジェクト2).someMethod();
不特定な引数で呼び出された事を確認する
※他にも、any()<-オブジェクト、any(Class<T>)<-任意の型のインスタンス、anyInt()<-任意の数値などがある
 verify(request).getAttribute(anyString());
呼び出されたメソッドに渡された引数の状態を確認する
ArgumentCaptor<Hoge> argument = new ArgumentCaptor<Hoge>();
verify(foo).someMethod(argument.capture());
Hoge hoge = argument.getValue();
assertEquals("XXX", hoge.toString());
呼び出されていない事を確認する
verify(request, never()).getAttribute(any(String.class));

既にインスタンス化されたオブジェクトの振る舞いを変える

 HttpSession session = spy(new HttpSession());
 when(session.getId()).thenReturn("ID");

コメントをかく


「http://」を含む投稿は禁止されています。

利用規約をご確認のうえご記入下さい

管理人/副管理人のみ編集できます