直接上代码
Calculator.java
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;
}
}
CalculatorTest.java
import org.junit.Test;
import static org.junit.Assert.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class CalculatorTest {
@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);
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 });
assertEquals(102, obj);
} catch (Exception e) {
fail("-----");
}
}
}
标签:name,--,age,单元测试,private,class,int,Calculator
From: https://www.cnblogs.com/hmy71/p/junit_9.html