0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Junitでprivateメソッドを呼び出す

Posted at

はじめに

現場でJunitからPrivateのメソッドを呼び出す必要が出てきたため方法を調査してみました。

準備

privateメソッドを定義する

	private int divNumbers(Integer a, Integer b) {
		return a - b;
    }

呼び出し

通常、下記のようにprivateメソッドを別のクラスから呼び出すことはできない

01.png

設定

リフレクションを利用することで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);
	}

実行結果

01.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?