zoukankan      html  css  js  c++  java
  • JUnit 3.8 通过反射测试私有方法

    测试私有(private)的方法有两种:

    1)把目标类的私有方法(修饰符:private)修改为(public),不推荐,因为修改了源程序不佳

    2)通过反射 (推荐

    代码演示:

    目标程序

    PrivateMethod.java

    [java] view plain copy
    1. package com.junit3_8;  
    2.   
    3. public class PrivateMethod {  
    4.     //私有方法  
    5.     private int add(int a, int b)  
    6.     {         
    7.         return a +b ;  
    8.           
    9.     }  
    10.   
    11. }  

    测试程序

    PrivateMethodTest.java

    [java] view plain copy
    1. package com.junit3_8;  
    2.   
    3. import java.lang.reflect.Method;  
    4.   
    5. import junit.framework.Assert;  
    6. import junit.framework.TestCase;  
    7.   
    8. /** 
    9.  * 通过反射测试私有方法, 
    10.  *  
    11.  */  
    12. public class PrivateMethodTest extends TestCase {  
    13.       
    14.     public void testAdd() throws Exception  
    15.     {  
    16.         //PrivateMethod pm = new PrivateMethod();  
    17.         //获取目标类的class对象  
    18.         Class<PrivateMethod> class1 = PrivateMethod.class;  
    19.           
    20.         //获取目标类的实例  
    21.         Object instance = class1.newInstance();  
    22.           
    23.         //getDeclaredMethod()  可获取 公共、保护、默认(包)访问和私有方法,但不包括继承的方法。  
    24.         //getMethod() 只可获取公共的方法  
    25.         Method method = class1.getDeclaredMethod("add", new Class[]{int.class,int.class});  
    26.           
    27.         //值为true时 反射的对象在使用时 应让一切已有的访问权限取消  
    28.         method.setAccessible(true);  
    29.           
    30.         Object result = method.invoke(instance, new Object[]{1,2});  
    31.           
    32.         Assert.assertEquals(3, result);  
    33.           
    34.       
    35.     }  
    36.   
    37. }  

    小结:

    getDeclaredMethod()  可获取 公共、保护、默认(包)访问和私有方法,但不包括继承的方法。 getMethod() 只可获取公共的方法

    Method method = class1.getDeclaredMethod("add", new Class[]{int.class,int.class});

    等价于

    Method method = class1.getDeclaredMethod("add", new Class[]{Integer.TYPE,int.Integer.TYPE});

     因为 Integer.TYPE 表示基本类型 int 的 Class 实例

  • 相关阅读:
    C#中 @ 的用法
    ASP.NET页面间传值
    ASP.NET中常用的文件上传下载方法
    把图片转换为字符
    把图片转换为字符
    JavaScript 时间延迟
    Using WSDLs in UCM 11g like you did in 10g
    The Definitive Guide to Stellent Content Server Development
    解决RedHat AS5 RPM安装包依赖问题
    在64位Windows 7上安装Oracle UCM 10gR3
  • 原文地址:https://www.cnblogs.com/hoobey/p/5293982.html
Copyright © 2011-2022 走看看