您的位置:首页 > 其它

JUnit Test——访问私有成员(Field和Method)

2007-12-12 16:27 316 查看
例1:




public class PrivateSample ...{


    private int counter;


   




    private void increment() ...{


        System.out.println("increment");


        counter++;


    }


}


import junit.framework.TestCase;


 




public class TestPrivateSample extends TestCase ...{


    public void testIncrement()


             throws NoSuchFieldException, NoSuchMethodException,




                    InvocationTargetException, IllegalAccessException ...{


        PrivateSample sample = new PrivateSample();


        Class sampleClass = sample.getClass();


 


        // get private property


        Field field = sampleClass.getDeclaredField("counter");


        // Make the field accessibe


        field.setAccessible(true);


        // get the value and have a test


        assertEquals(0, field.getInt(sample));


 


        // get private method




        Class[] params = new Class[]...{};


        Method method = sampleClass.getDeclaredMethod("increment", params);


        // Make the methodaccessibe


        method.setAccessible(true);


        // execute


        method.invoke(sample, null);


 


        // get the value again and test it


        assertEquals(1, field.getInt(sample));


    }


}

例2:


import java.lang.reflect.Method;






class MethodTest ...{




  private final String sayHello(final String name) ...{


    return "Hello, " + name;


  }


}






public class Test9 ...{


  public static void main(String args[])  throws Exception ...{


    MethodTest test = new MethodTest();


    final Method[] methods = test.getClass().getDeclaredMethods();




    for (int i = 0; i < methods.length; ++i) ...{




      if (methods[i].getName().equals("sayHello")) ...{




        final Object params[] = ...{"Ross"};


        methods[i].setAccessible(true);


        Object ret = methods[i].invoke(test, params);


        System.out.println(ret);


      }


    }


  }


}

其实,测试私有成员,只要对Java的反射技术有所了解就可以。参照下Java帮助文档
Field     getField(String name)   返回一个 Field 象,它反映此 Class 象所表示的或接口的指定公共成字段。
Field[]     getFields()   返回一个包含某些 Field 象的数,些象反映此 Class 象所表示的或接口的所有可公共字段。
Field     getDeclaredField(String name)   返回一个 Field 象,象反映此 Class 象所表示的或接口的指定已声明字段。
Field[]     getDeclaredFields()    返回 Field 象的一个数,些象反映此 Class 象所表示的或接口所声明的所有字段,包括公共、保、默(包)和私有字段,但不包括承的字段。
Method     getDeclaredMethod(String name, Class... parameterTypes)   返回一个 Method 象,象反映此 Class 象所表示的或接口的指定已声明方法。
Method[]     getDeclaredMethods()   返回 Method 象的一个数,些象反映此 Class 象表示的或接口声明的所有方法,包括公共、保、默(包)和私有方法,但不包括承的方法。
Method     getMethod(String name, Class... parameterTypes)   返回一个 Method 象,它反映此 Class 象所表示的或接口的指定公共成方法。
Method[]     getMethods()  返回一个包含某些 Method 象的数,些象反映此 Class 象所表示的或接口(包括那些由或接口声明的以及从超和超接口承的那些的或接口)的公共 member 方法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息