私有方法的单元测试

直接上例子


待测试的类
public class Calculator {
private int count = 0;

private int add(int a, int b) {
return a + b;
}

private void increase() {
count++;
}

}


测试Calculator的testcase。
public class CalculatorTest extends TestCase {
private final Calculator calculator = new Calculator();

public void testAdd() {
Class clazz = calculator.getClass();
try {

Method addMethod = clazz.getDeclaredMethod("add", int.class, int.class);//jdk新特性:可变参数
addMethod.setAccessible(true);//设置该方法可见
Integer result = (Integer) addMethod.invoke(calculator, 5, 6);//jdk新特性:可变参数
assertEquals(11, result.intValue());
} catch (Exception e) {
assertTrue(false);
}
}

public void testIncrease() {
Class clazz = calculator.getClass();
try {
Field countField = clazz.getDeclaredField("count");
countField.setAccessible(true);//设置该字段可见
Integer count = (Integer) countField.get(calculator);

Method increaseMethod = clazz.getDeclaredMethod("increase");
increaseMethod.setAccessible(true);
increaseMethod.invoke(calculator);
Integer count2 = (Integer) countField.get(calculator);
assertEquals((Integer) (count + 1), count2);
} catch (Exception e) {
e.printStackTrace();
assertTrue(false);
}
}
}

你可能感兴趣的:(私有方法的单元测试)