そういえば書いてなかったのでメモ。
/** * Hogeクラスのprivateメソッドadd(int a, int b)をテストする * @throws SecurityException * @throws IllegalArgumentException * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InvocationTargetException */ public void testAdd() throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Hoge hoge = new Hoge(); Class<Hoge> clz = Hoge.class; Method method = clz.getDeclaredMethod("add", Integer.class, Integer.class); method.setAccessible(true); int result = (int) method.invoke(hoge, 5, 3); asserTrue(result == 8); }
■staticメソッド
/** * Hogeクラスのprivate staticメソッドadd(int a, int b)をテストする * @throws SecurityException * @throws IllegalArgumentException * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InvocationTargetException */ public void testAdd() throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException { Class<Hoge> clz = Hoge.class; Method method = clz.getDeclaredMethod("add", Integer.class, Integer.class); method.setAccessible(true); int result = (int) method.invoke(clz, 5, 3); asserTrue(result == 8); }
■プライベートフィールド
Hoge hoge = new Hoge(); Field f = hoge.getClass().getDeclaredField("f"); f.setAccessible(true); assertEquals(value, f.get(hoge)); //assertEquals(Piyo.class, f.get(hoge).getClass());