JUnitユニットテスト(5)−反射テストによるプライベートメソッド


JUnitユニットテスト(5)−反射テストによるプライベートメソッド
プライベート(private)をテストする方法は2つあります.
1)ターゲットクラスのプライベートメソッド(修飾子:private)を(public)に変更し、ソースプログラムを変更したため推奨しません.
2)反射(推奨)
前提条件:
PrivateMethod.java
package com.junit3_8;  
  
public class PrivateMethod {  
    //    
    private int add(int a, int b)  
    {         
        return a +b ;      
    }  
  } 

試験手順:PrivateMethodTest.java
package com.junit3_8;

import java.lang.reflect.Method;
import junit.framework.Assert;
import junit.framework.TestCase;

/**
 *  ,
 * 
 */
public class PrivateMethodTest extends TestCase {
	
	public void testAdd() throws Exception
	{
		//PrivateMethod pm = new PrivateMethod();
		// class 
		Class<PrivateMethod> class1 = PrivateMethod.class;
		
		// 
		Object instance = class1.newInstance();
		
		//getDeclaredMethod()     、 、 ( ) , 。
		//getMethod()  
		Method method = class1.getDeclaredMethod("add", new Class[]{int.class,int.class});
		
		// true     
		method.setAccessible(true);
		
		Object result = method.invoke(instance, new Object[]{1,2});
		
		Assert.assertEquals(3, result);
			
	}

}

PS:
getDeclaredMethod()は、公開、保護、デフォルト(パッケージ)アクセス、およびプライベートメソッドを取得できますが、継承メソッドは含まれません.getMethod()は、共通のメソッドのみを取得できます.