zoukankan      html  css  js  c++  java
  • Junit3.8 私有方法测试

    1. 测试类的私有方法时可以采取两种方式:
    1) 修改方法的访问修饰符,将private修改为default或public(但不推荐采取这种方式)。
    2) 使用反射在测试类中调用目标类的私有方法(推荐)。

     1 package junit;
     2 
     3 public class Calculator2
     4 {
     5     private int add(int a, int b)
     6     {
     7         return a + b;
     8     }
     9 }
    10 
    11 
    12 package junit;
    13 
    14 import java.lang.reflect.Method;
    15 
    16 import junit.framework.Assert;
    17 import junit.framework.TestCase;
    18 /**
    19  * 测试私有方法,反射
    20  */
    21 public class Calculator2Test extends TestCase
    22 {
    23     public void testAdd()
    24     {
    25         try
    26         {
    27             Calculator2 cal2 = new Calculator2();
    28 
    29             Class<Calculator2> clazz = Calculator2.class;
    30 
    31             Method method = clazz.getDeclaredMethod("add", new Class[] {
    32                     Integer.TYPE, Integer.TYPE });
    33 
    34             method.setAccessible(true);
    35 
    36             Object result = method.invoke(cal2, new Object[] { 2, 3 });
    37 
    38             Assert.assertEquals(5, result);
    39 
    40         }
    41         catch (Exception ex)
    42         {
    43             Assert.fail();
    44         }
    45 
    46     }
    47 }
  • 相关阅读:
    攻防世界-web进阶-Web_php_include
    攻防世界-web进阶-php_rce
    Buuctf-misc-穿越时空的思念
    Buuctf-misc-[BJDCTF 2nd]EasyBaBa (kinovea)
    Buuctf-misc-菜刀666
    Buuctf-misc-[BJDCTF 2nd]圣火昭昭-y1ng(outguess)
    Access数据库简介
    VC与VB
    VB的使用
    工作总结2
  • 原文地址:https://www.cnblogs.com/daneres/p/4688876.html
Copyright © 2011-2022 走看看