LoginSignup
8
5

More than 5 years have passed since last update.

Java でもa == 1 && a == 2 && a == 3でtrueって出力させたい(PowerMockito編)

Last updated at Posted at 2018-01-24

前書き

もっと簡単に、だけどちょっとズルい方法で実現しました。
タイトルの通り、PowerMockitoを使います。

コード

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;

@RunWith(PowerMockRunner.class)
public class MyTest {

    @Test
    public void test() {
        final Integer a = mock(Integer.class);
        when(a.intValue()).thenReturn(1, 2, 3);
        assertTrue(a == 1 && a == 2 && a == 3);
    }
}

ちょっと解説

PowerMockitoはご存知のとおり、finalクラスのモックをつくって、いろいろさせることができるライブラリです。
オートアンボクシングによりIntegerオブジェクトとプリミティブのint==で比較できます。
また、オートアンボクシングでInteger#intValueが呼ばれるので、このときに返す値を、PowerMockitoで順番に指定したのでした。

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