Junit 测试私有方法和私有变量方法

//测试私有方法
Method method = targetClass.getDeclaredMethod(methodName, argClasses);
method.setAccessible(true);
return method.invoke(targetObject, argObjects);
//测试私有变量
Field field = targetClass.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, value);
翻译一下
Method method = targetClass.getDeclaredMethod("方法名", 方法参数类型);
method.setAccessible(true);
return method.invoke(类的实例, 方法参数值);

Field field = targetClass.getDeclaredField("私有变量名");
field.setAccessible(true);
field.set(类的实例, 私有变量值);
------------------------------------------------------------------------------------
实例
  class NumParser(){
  //私有变量
  private Query query_;
  public  NumParser(Query query){
     //构造函数
     query_ = query
   }
   private void fun(){
       //私有方法
   }
 }
    NumParser numParser = new NumParser(query)
    Method method = numParser.getClass().getDeclaredMethod("fun", null);
    method.setAccessible(true);
    method.invoke(numParser, null);
             
    Field field = numParser.getClass().getDeclaredField("query_");
    field.setAccessible(true);
    Object after = field.get(numParser);
    
//多种参数的写法***********************************************************************
Method method = numParser.getClass().getDeclaredMethod("fun", new Class[]{int.class,int.class});

Object result = method.invoke(cal, new Object[]{1,10});


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值