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 }

 

posted @ 2015-07-30 11:52  淡纷飞菊  阅读(334)  评论(0编辑  收藏  举报