LoginSignup
30
33

More than 5 years have passed since last update.

JUnit備忘録

Last updated at Posted at 2018-01-18

JUnitの備忘録を記載していく。

Assert

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.fail;

// actual = expectの場合、正常
assertThat(actual, is(expect));
// actual != expectの場合、正常
assertThat(actual, is(not(expect)));
// エラー
fail("error reason");

Mockito

mockオブジェクトの作成
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;

// オブジェクト全体をモック化する場合
Target targetMock = mock(Target.class);
// モック設定したメソッドのみをモック化する場合
Target targetMock = spy(Target.class);
voidメソッドのmock化
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;

// 正常終了させる
doNothing().when(targetMock).targetMethod(anyString(), any(Parameter.class));

// 例外をスローする ※対象メソッドがThrowsする例外またはRuntimeExceptionが指定可能
doThrow(new RuntimeException()).when(targetMock).targetMethod("01");

上記の場合、targetMethodメソッドが引数"01"で呼び出された時に例外をスローする。
任意の引数が渡された場合にモックを動作させる場合は、Stringの場合はanyString()、オブジェクトの場合はany(クラス名)などを指定する。

戻り値のあるメソッドのmock化
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;

// 戻り値に"ok"を返却する
when(targetMock.targetMethod(anyString())).thenReturn("ok");

// 1回目と3回目の実行に"ok"、2回目の実行に"ng"を返却する
when(targetMock.targetMethod(anyString())).thenReturn("ok", "ng", "ok");

// 例外をスローする ※対象メソッドがThrowsする例外またはRuntimeExceptionが指定可能
when(targetMock.targetMethod(anyString())).thenThrow(new RuntimeException());
mockメソッドのassert
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

// メソッド実行回数の確認
// targetMethodメソッドが1回だけ実行されたことを確認する
verify(targetMock, times(1)).targetMethod(anyString(), anyString());
Mockitoの注意点
  • publicメソッドのみmock化が可能

  • staticメソッドはmock化できない

  • @InjectMocksによるモックのインジェクションは@InjectMocksで指定したクラスの直のプロパティに対して摘要される。
    つまり、@Injectオブジェクトの中の@Injectに対してはモックをインジェクションしてくれない。
    実現したい場合は、リフレクションを使ってモックを直接、変数に突っ込む必要がある。

30
33
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
30
33