现在的位置: 首页 > 综合 > 正文

JUnit单元测试(五)--通过反射测试私有方法

2013年10月14日 ⁄ 综合 ⁄ 共 968字 ⁄ 字号 评论关闭

JUnit单元测试(五)--通过反射测试私有方法

测试私有(private)的方法有两种:

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() 只可获取公共的方法。

抱歉!评论已关闭.