junit怎样测试私有化方法两个参数其中有可变参的方法?

问题描述:

img

junit怎样测试私有化方法两个参数其中有可变参的方法?
首先要明白参数不是方法,所以你主要应该要问junit怎样测试私有化方法,和参数无关
junit测试私有化方法看下面的示例代码:

public class calcutate2{
    
    private static String stringtest;
    
    public void  setvalue(String temp){
    
     stringtest=temp+"123";  //get value: stringtest
    
    }
 
    public String getvalue(){  //return the stringtest value for unit test
 
     return stringtest;
    
    }
}
import org.junit.Assert;
import java.lang.reflect.Method;
import org.junit.Test;
public class PrivateTest {
 
 @Test
 @SuppressWarnings("unchecked")
 public void testAdd()
 {
  calcutate2 cal = new calcutate2();
  Class c = calcutate2.class;//获得class类
  try
  {
   Method method = c.getDeclaredMethod("add", new Class[]{int.class,int.class});//获得method.注意,这里不能使用getMethod方法,因为这个方法只能获取public修饰的方法..
   method.setAccessible(true);//这个设置为true.可以无视java的封装..不设置这个也无法或者这个Method
   Object result = method.invoke(cal, new Object[]{1,10});
   Assert.assertEquals(11, result);//这里自定拆箱..
  }
  catch (Exception e)
  {
   e.printStackTrace();
  }
 }
}

主要是靠反射技术,你的图片中可变长参数,其实就是一个数组而已