junit测试private私有变量和私有方法

发表于:2021-8-06 09:45

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:李小期    来源:知乎

  这是源代码:
  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),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号