1
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?

More than 5 years have passed since last update.

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

1
Last updated at Posted at 2018-08-10

背景

今日JUnitで書かれたテストコードを見ていたらprivateメソッドのテストが書かれていなかった。privateメソッドを呼び出すサンプルを作ったので投稿しようかと思いました。

追記
詳しくは@Kilisame様のコメントを参照して頂きたいのですが、privateのテストを忘れてたからテストしました、と言う主旨の記事ではありません。呼び出し側のpublicのテストが出来ないと言うか大変と言うか....(お察し頂きたい)感じなので、せめてprivateのテストをしたくて書いてみました。

コード

import static org.junit.Assert.*;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

/** サンプルクラス*/
public class private_Test {

	public class Sample{
		private int fuge(int i) {
			return i;
		}
	}
	
	@Test
	public void test() {
		
		Sample sample = new Sample();
		try {
			Method method = Sample.class.getDeclaredMethod("fuge", int.class);
			method.setAccessible(true);
			int rtn = (int)method.invoke(sample, 2);
			assertEquals(2,rtn);
			
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
		}
	}

}

getDeclaredMethod()メソッドでメソッドを取得し、setAccessible(true)で外部アクセスを許可、method.invoke()で実行できます。

1
0
2

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
1
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?