10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mockitoチートシート

Last updated at Posted at 2018-10-20

Mockitoって?

Javaのテスト環境で、モジュールの振る舞いを「モック化」する事ができる。

基本的には以下の流れで使用できる。

  1. 対象クラス、インターフェイスを指定しモックオブジェクトを取得。
  2. モックオブジェクトの振る舞いを設定(オプション)
  3. バリデーション

モック化

mockメソッドを使用する場合

List mockedList = mock(List.class);

@Mockアノテーションを使用する場合

public class HogeTest {

  @Mock List list;

  @Before
  public void before() {
    MockitoAnnotations.initMocks(this);
  }

}

振る舞いを設定

戻り値を設定

when(mockedList.get(0)).thenReturn("zero");

例外のスローを設定

when(mockedList.get(1)).thenThrow(new IllegalArgumentException());

バリデーション

メソッドの呼び出しを確認

verify(mockedList).get(0);

メソッドの呼び出しを確認(非同期)

verify(mockedList, timeout(1000)).get(0);

参考資料

10
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?