【Java】 PowerMock ~ 入門編 ~

【1】公式サイト

https://github.com/powermock/powermock

【2】初期設定

* Gradleを使う

build.gradle

dependencies {
    // PowerMock
    testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '1.7.3'
    testCompile group: 'org.powermock', name: 'powermock-api-mockito2', version: '1.7.3'
}

【3】サンプル

例1:Calendar.getInstance()のモック化

* Calendar.getInstance()をモック化する

DateUtil.java (テスト対象)

import java.util.Calendar;
import java.util.Date;

public class DateUtil {
  public static Date getCurrentDate() {
    // 内部で、Calendar.getInstance()を呼んでいる
    Calendar calendar = Calendar.getInstance();
    return calendar.getTime();
  }
}

DateUtilTest.java (テストコード)

import static org.junit.Assert.*;

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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class) // ★重要★
@PrepareForTest({Calendar.class, DateUtil.class}) // ★重要★
public class DateUtilTest {

  @Test
  public void getCurrentDateTest() {
    Calendar mockCalendar = Calendar.getInstance();
    mockCalendar.set(2018, 1, 9, 22, 20, 9);
    mockCalendar.set(Calendar.MILLISECOND, 0);
    PowerMockito.mockStatic(Calendar.class);
    PowerMockito.when(Calendar.getInstance()).thenReturn(mockCalendar);

    Date result = DateUtil.getCurrentDate();

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    System.out.println("Date : " + simpleDateFormat.format(result));
    assertEquals("2018/02/09 22:20:09", simpleDateFormat.format(result));
  }
}

例2:System.getenv()のモック化

* 環境変数の取得 System.getenv()をモック化する

SampleTest.java (テストコード)

import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class) // ★重要★
@PrepareForTest({System.class}) // ★重要★
public class SampleTest {

  @Test
  public void test() {
    PowerMockito.mockStatic(System.class);
    PowerMockito.when(System.getenv("ENV_KEY")).thenReturn("dummy01");

    assertEquals("dummy01", System.getenv("ENV_KEY"));
  }
}

関連記事

Mockito ~ 入門編 ~
https://dk521123.hatenablog.com/entry/2014/07/18/233904
Mockito ~ 基本編 ~
https://dk521123.hatenablog.com/entry/2014/07/19/121409