JUnit 3.8 通过反射测试私有方法

测试私有(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);
}
}

小结:
getDeclaredMethod() 可获取 公共、保护、默认(包)访问和私有方法,但不包括继承的方法。
getMethod() 只可获取公共的方法
Method method = class1.getDeclaredMethod("add", new Class[]{int.class,int.class});
等价于
Method method = class1.getDeclaredMethod("add", new Class[]{Integer.TYPE,int.Integer.TYPE});
因为 Integer.TYPE 表示基本类型 int 的 Class 实例

原文连接:http://blog.csdn.net/hzc543806053/article/details/7340546

猜你喜欢

转载自lovelease.iteye.com/blog/1750562
3.8
今日推荐