根据反射机制测试private方法(junit测试)

来源:互联网 发布:数组冒泡排序php 编辑:程序博客网 时间:2024/05/16 02:02

需要测试的方法

package com.test.junit;

public class Calucator2 {

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

//  单元测试类

 

package com.test.junit;

import java.lang.reflect.Method;

import junit.framework.Assert;
import junit.framework.TestCase;

public class Calucator2Test extends TestCase {

 
 public void testAdd(){
  
  try{
  Calucator2 ct2=new Calucator2();
  
  Class<Calucator2> clazz=Calucator2.class;
  
  Method method=clazz.getDeclaredMethod("add",new Class[]{Integer.TYPE,
    Integer.TYPE});
  method.setAccessible(true);
  
  
  Object result=method.invoke(ct2, new Object[]{2,5});
  
  Assert.assertEquals(7, result);
  
  }catch(Exception e){
   
   Assert.fail();
  }
  
  
 }
 
}