White Box技術部

WEB開発のあれこれ(と何か)

テストパターン(Factoryのモック)

MockitoとPowerMockで、返却値がabstractクラスのFactoryメソッドをモックする感じのコード。

@RunWith(PowerMockRunner.class)
@PrepareForTest({SomeFactory.class})
public class SomeTestClass_SomeMethodTest {

    @Test
    public void 作成したインスタンスのメソッドを呼び出した際のエラー処理確認() {
        SomeTestClass testSuite = new SomeTestClass();

        PowerMockito.mockStatic(SomeFactory.class);

        SomeAbstractClass mockedInstance = mock(SomeAbstractClass.class);
        when(SomeFactory.newInstance()).thenReturn(mockedInstance);

        // 後はmockedInstanceを好きにモックする。
        // 例えば特定メソッドでエラーを投げるには、
        // そのメソッドが発生させうるExceptionかRuntimeExceptionをthenThrowで投げる
        UnexpectedValueException uvEx =
                new UnexpectedValueException("exception by mock.");
        when(mockedInstance.getSpecialValue()).thenThrow(uvEx);

        try {
            testSuite.someMethod();
            fail("doesn't happened exception!");

        } catch (UnexpectedValueException e) {
            assertEquals("exception by mock.", e.getMessage());
        }
    }
}

mock()使えば、実装クラスがライブラリ依存でも、簡単にモックできるのは良い感じですね。

登場しているクラス・メソッドは、JUnit関連やMockitoとPowerMock、Whitebox以外はダミーです。