2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JUnitでprivateメソッドをテストする

Posted at

手順

  1. 実装クラスのインスタンスを作成する
  2. privateメソッドのインスタンスを作成する
  3. privateメソッドへのアクセスを許可する
  4. インスタンス化したメソッドに実装クラスのインスタンスと、メソッドの引数を渡す

サンプルコード

TargetClass.java
private String privateMethod(String message) {
	return "Input: " + message;
}
TargetClassTest.java
@Test
public void privateMethodTest() {

	// 1. 実装クラスのインスタンスを作成する
	TargetClass targetClass = new TargetClass();

	// 2. privateメソッドのインスタンスを作成する
	Method privateMethod = TargetClass.class.getDeclaredMethod("privateMethod", String.class);

	// 3. privateメソッドへのアクセスを許可する
	privateMethod.setAccessible(true);

	// 4. インスタンス化したメソッドに実装クラスのインスタンスと、メソッドの引数を渡す
	String actual = (String) privateMethod.invoke(targetClass, "Oh my god.");
	String expected = "Input: Oh my god.";

	// Assert
	assertEquals(expected, actual);
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?