您的位置:首页 > 其它

Junit3.8 私有方法测试

2016-05-11 00:00 423 查看
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
7fe0
Assert.assertEquals(5, result); 39
40  } 41         catch (Exception ex) 42  { 43  Assert.fail(); 44  } 45
46  } 47 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: