|
当たり前の話しですが、privateメソッドは、他のクラスから呼べません。
しかし単体テストなどで、どうしても呼びたくなります。
以下、reflectionを使った参考。
テストする側のクラスには、
import java.lang.reflect.Method;
を使用します。
//テスト対象のクラス
public class HelloWorld {
//引数なし
private int pMethod() {
System.out.println("aa");
return 1;
}
//引数あり
private String pMethod1(String str1, String str2) {
System.out.println(str1 + " " + str2 );
return "private!";
}
}
//テストする側
import java.lang.reflect.Method;
テストクラス
public void test() throws Exception{
// クラス取得
Class<HelloWorld> c = HelloWorld.class;
// //引数なしのメソッドテスト
// // メソッド取得(メソッド名を文字列として指定)
// Method m = c.getDeclaredMethod("pMethod");
//
// // Privateメソッドの場合、以下の設定が必要
// m.setAccessible(true);
//
// Integer ret = (Integer) m.invoke(c.newInstance());
// System.out.println(ret);
// -----
// 引数の分、クラス型の配列を定義する。
Class[] args = { String.class, String.class };
Method m = c.getDeclaredMethod("pMethod1", args);
String str1 = "ABC, ZZZ";
String str2 = "9876543210";
m.setAccessible(true);
// 第二引数以降にメソッドに渡す引数をセット
String ret = (String) m.invoke(c.newInstance(), str1, str2);
System.out.println(ret);
}
|