Mockitoを利用したテスト時に、スタティックなメソッドのモック化と例外のスロー方法についてのメモになります。
事前準備
今回のテスト用に以下のコードを作成します。
- TestUtilクラス:テスト用のユーティルクラスでスタティックなメソッド(getNum())で固定値を返す
- UseUtilクラス:TestUtil.getNum()を使用するクラス
- TestException:テスト用の例外クラス
// TestUtil.java public class TestUtil { public static Integer getNum() { return 1; } }
// UseUtil.java public class UseUtil { public Integer useUtilGet() throws TestException { Integer num = null; try { num = TestUtil.getNum(); } catch (TestException e) { throw new TestException(e.getMessage()); } return num; } } class TestException extends RuntimeException { String msg; TestException(String msg) { this.msg = msg; } public String getMessage() { return this.msg; } }
テストコードの作成
以下が作成したテストコードとなります。
// UseUtilTest.java @RunWith(PowerMockRunner.class) @PrepareForTest({ TestUtil.class }) public class UseUtilTest { @InjectMocks private UseUtil util = new UseUtil(); @Before public void setup() { MockitoAnnotations.openMocks(this); // staticメソッドを持つクラスのモック化 PowerMockito.mockStatic(TestUtil.class); } @After public void tearDown() throws Exception { } @Test public void testUtil() { PowerMockito.when(TestUtil.getNum()).thenReturn(100); try { int num = this.util.useUtilGet(); MatcherAssert.assertThat(num, CoreMatchers.is(100)); } catch (Exception e) { e.printStackTrace(); fail(); } } @Test public void testUtilException() { PowerMockito.doThrow(new TestException("test")).when(TestUtil.class); TestUtil.getNum(); try { this.util.useUtilGet(); } catch (TestException e) { e.printStackTrace(); MatcherAssert.assertThat(e.getMessage(), CoreMatchers.is("test")); } catch (Exception e) { e.printStackTrace(); fail(); } } }
staticなメソッドを持つクラスをモック化するには、@PrepareForTest({ クラス名.class })
を付与します。
そして使用する際に、PowerMockito.mockStatic(TestUtil.class);
で宣言をします(今回は初期化メソッド内に記述しました)。
構文は以下の通りとなります。
また例外をスローする際はdoThrow(...).when(...)
で例外の設定をしてから、対象のメソッドを記述します。