はじめに
現場でJunitからPrivateのメソッドを呼び出す必要が出てきたため方法を調査してみました。
準備
privateメソッドを定義する
private int divNumbers(Integer a, Integer b) {
return a - b;
}
呼び出し
通常、下記のようにprivateメソッドを別のクラスから呼び出すことはできない
設定
リフレクションを利用することでprivateメソッドが呼び出せる様になる
@Test
public void test2() throws NoSuchMethodException, SecurityException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method method = Calc.class.getDeclaredMethod("divNumbers", Integer.class, Integer.class);
method.setAccessible(true);
Calc c = new Calc();
int div = (int)method.invoke(c, 30, 10);
assertEquals(20, div);
}