JUnit4--测试私有方法
package com.test.junit3;
public class calcutate2 {
private int add(int a, int b) {
return a + b;
}
}
package com.test.junit3;
import org.junit.Assert;
import java.lang.reflect.Method;
import org.junit.Test;
public class privateTest {
@Test
@SuppressWarnings("unchecked")
public void testAdd()
{
calcutate2 cal = new calcutate2();
Class c = calcutate2.class;//获得class类
try
{
Method method = c.getDeclaredMethod("add", new Class[]{int.class,int.class});//获得method.注意,这里不能使用getMethod方法,因为这个方法只能获取public修饰的方法..
method.setAccessible(true);//这个设置为true.可以无视java的封装..不设置这个也无法或者这个Method
Object result = method.invoke(cal, new Object[]{1,10});
Assert.assertEquals(11, result);//这里自定拆箱..
}
catch (Exception e)
{
e.printStackTrace();
}
}
}