7
5

More than 5 years have passed since last update.

jUnit4+PowerMock+EasyMockでstaticメソッドをモック

Last updated at Posted at 2016-01-15

情報はいろいろあるけど、なかなかうまくできなかったのでメモ。

環境

  • Java8
  • jUnit4.12
  • PowerMock1.6.4
  • EasyMock3.4

mavenなら以下を入れればOK

  • powermock-module-junit4 1.6.4
  • powermock-module-easymock 1.6.4
  • easymock 3.4

テスト対象コード

Utils.java
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Utils {
    public static String getStringDate() {
        Calendar cal = Calendar.getInstance();
        return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
    }
}

「Calendar.getInstance()」をいつ実行しても同じ値を返すようにモック化したい。

テストコード

UtilsTest.java
import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;

import java.util.Calendar;

import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class) // *1
public class UtilTest {

    @Test
    public void test() {
        Calendar cal = Calendar.getInstance();
        cal.set(2015, 3, 1);

        // *2
        PowerMock.mockStaticPartial(Calendar.class, "getInstance");
        EasyMock.expect(Calendar.getInstance()).andReturn(cal);
        PowerMock.replay(Calendar.class);

        String actual = Utils.getStringDate();
        assertThat(actual, is("20150401")); 
    }
}

*1の箇所ではテストするメソッドがあるクラスを指定。
*2の箇所ではモックしたいメソッドのあるクラス周りの設定。

staticメソッドを呼び出すクラスを指定しなければいけないところを勘違いしていて、つまづいていました。

7
5
2

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