LoginSignup
0
1

More than 1 year has passed since last update.

Powermock WhiteBoxでprivateメソッドをテスト

Posted at

はじめに

Junitテストケースを書く際に、privateメソッドのテストコードを比較的に書きにくいです。
invokeで書くのは一般的ですが、PowermockのWhiteBoxのメソッドを使うと便利です。

Invokeのテスト例

メソッド

public class UserUtil {
  private String getYourName(String lastName, String firstName) {
    return lastName + " " + firstName;
  }
}

テストコード

import static org.junit.Assert.assertEquals;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class UserUtilTest {

  @Test
  public void getYourName_useInvoke()
      throws NoSuchMethodException, SecurityException, IllegalAccessException,
          IllegalArgumentException, InvocationTargetException {

    UserUtil userUtil = new UserUtil();

    Method method = UserUtil.class.getDeclaredMethod("getYourName", String.class, String.class);
    method.setAccessible(true);

    String actual = (String) method.invoke(userUtil, "山田", "太郎");

    assertEquals("山田 太郎", actual);
  }
}

テストコードはちょっと長いです。

Powermock WhiteBoxの使う例

Powermockとは

image.png

staticメソッド、privateメソッドのmockをしやすくなります。

powermock-reflectとは

Gradleにpowermock-reflectを追加

build.gradle
    // https://mvnrepository.com/artifact/org.powermock/powermock-reflect
    testImplementation group: 'org.powermock', name: 'powermock-reflect', version: '2.0.9'

WhiteBoxのテスト例

  @Test
  public void getYourName_useWhiteBox() throws Exception {

    UserUtil userUtil = new UserUtil();

    String actual = (String) Whitebox.invokeMethod(userUtil, "getYourName", "山田", "太郎");

    assertEquals("山田 太郎", actual);
  }

簡潔に記載できました。

そのたメソッド

image.png

以上

0
1
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
0
1