这是源代码:
package privateTest;
public class Calculator {
private String name;
private int age;
public Calculator(String name, int age) {
this.name = name;
this.age = age;
}
private int add(int a, int b) {
return a + b;
}
}
下面的是单元测试代码,使用的是junit4,如下:
package privateTest;
import org.junit.Test;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import junit.framework.Assert;
import junit.framework.TestCase;
import privateTest.Calculator;
public class CalculatorTest extends TestCase {
@Test
public void testAgeField() throws IllegalArgumentException,
IllegalAccessException {
String name = "lixiaoqi";
int age = 100;
Field[] fa = Calculator.class.getDeclaredFields();
for (Field f : fa) {
if (f.getName().equals("age")) {
f.setAccessible(true);
Calculator calculator = new Calculator(name, age);
int result = (int) f.get(calculator);
Assert.assertEquals(age, result);
}
}
}
@Test
public void testAddMethod() {
String name = "lixiaoqi";
int age = 100;
Calculator c = new Calculator(name, age);
Class<Calculator> cal = Calculator.class;
try {
Method method = cal.getDeclaredMethod("add", new Class[] {
int.class, int.class });
method.setAccessible(true);
Object obj = method.invoke(c, new Object[] { 100, 2 });
Assert.assertEquals(102, obj);
} catch (Exception e) {
Assert.fail("-----");
}
}
}
运行效果如下:
本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理