LoginSignup
2
5

More than 3 years have passed since last update.

JUnit + Mockito + PowerMock チートシート

Last updated at Posted at 2020-12-03

目次

使用環境

フレームワーク バージョン
JUnit 4.12
Mockito 2.7.22
PowerMock 1.7.4

モック-スパイオブジェクトの生成

モックオブジェクト

@Mock
Sample SampleMock;

スパイオブジェクト

@Spy
Sample SampleSpy = new Sample();

モックオブジェクト(PowerMockito)

Sample SamplePowerMockitoMock = PowerMockito.mock(Sample.class);

スパイオブジェクト(PowerMockito)

Sample SamplePowerMockitoSpy = PowerMockito.spy(new Sample());

メソッドのスタブ化

publicメソッド

doReturn(2020).when(SampleMock).getYear();

privateメソッド

PowerMockito.doReturn(2020).when(SampleMock, "getYear");

インスタンス生成のスタブ

PowerMockito.whenNew(Sample.class).withAnyArguments().thenReturn(SampleMock);

staticメソッド

※PrepareForTest に Sample.class を追加のこと

PowerMockito.mockStatic(Sample.class);
when(Sample.getYear()).thenReturn(2020);

protected-private変数の設定-取得

非static変数の設定

Whitebox.setInternalState(SampleInstance, "year", 2020);

非static変数の取得

int actualYear = Whitebox.getInternalState(SampleInstance, "year");

static変数の設定

Field field = Sample.class.getDeclaredField("year");
field.setAccessible(true);
field.set(null, 2020);

static変数の取得

Field field = Sample.class.getDeclaredField("year");
field.setAccessible(true);
int actualYear = (int)field.get(null);

メソッドの実行

protected, privateメソッド

Whitebox.invokeMethod(SampleInstance, "getYear");

メソッドの実行回数の検証

publicメソッド

verify(SampleMock, times(1)).getYear();

引数の型が合っていればよい場合

verify(SampleMock, times(1)).getYear(ArgumentMatchers.any(String.class));

protected, privateメソッド

PowerMockito.verifyPrivate(SampleMock, times(1)).invoke("getYear");

staticメソッド

PowerMockito.verifyStatic(Sample.class);
Sample.getYear();

その他

suppress

※ PrepareForTest に Sample.class を追加のこと

PowerMockito.suppress(PowerMockito.method(Sample.class, "getYear"));

replace

※ PrepareForTest に Sample.class を追加のこと

Method method = SampleInstance.getClass().getMethod("getYear");
PowerMockito.replace(method).with(
    new InvocationHandler() {
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            return 2020;
         }
    }
);

ArgumentCaptor

source.java
hogehoge.setSample(new Sample(){
    @override
    public int getYear(){
        return 2020;
    }
})

※ hogehoge に hogehogeMock を代入のこと

test.java
ArgumentCaptor<Sample> SampleCaptor = ArgumentCaptor.forClass(Sample.class);
verify(hogehogeMock, times(1)).setSample(SampleCaptor.capture());
Sample SampleObj = SampleCaptor.getValue();

参考文献

2
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
2
5