软件测试---私有方法的调用(Java反射机制)

1.私有构造方法如何实例化类?

public class MSD {
	private int a;
	private String b;
	//无参构造方法
	private MSD() {
	}
	//有参构造方法
	private MSD(int a, String b){
		this.a = a;
		this.b = b;
	}
}

测试类

import static org.junit.Assert.*;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


//无参构造方法的调用

    @Test
    public void testMSD(){
    	Class msdClass = MSD.class;
    	Constructor msdConstructor;
    	msdConstructor = msdClass.getDeclaredConstructor(int.class,String.class);
    	msdConstructor.setAccessible(true);
    	MSD msd = (MSD) msdConstructor.newInstance();//有参构造方法的调用

    @Test
    public void testMSD2(){
   	 	Class msdClass = MSD.class;
		Constructor msdConstructor;
    	msdConstructor = msdClass.getDeclaredConstructor();
    	msdConstructor.setAccessible(true);
    	MSD msd = (MSD) msdConstructor.newInstance(new Object[]{1,"1及此字符串	为参数值"});
    }

2.私有方法如何调用?
私有方法

    private static void insertion(int[] a, int lo, int hi, int d) {
    	for (int i = lo; i <= hi; i++)
    		for (int j = i; j > lo && a[j] < a[j - 1]; j--)
    			exch(a, j, j - 1);
    }

测试类

		@Test
	public void insertionTest(){
		// Method insertion = 类名.class.getDeclaredMethod("方法名",参数类);
        Method insertion = MSD.class.getDeclaredMethod("insertion",int[].class,int.class,int.class,int.class);
       	insertion.setAccessible(true);
        //insertion.invoke(类的实例,参数;
        insertion.invoke(msd,a,1,6,1);
      }

你可能感兴趣的:(软件测试)