Juint 3.8之菜鸟简记(二)

Junit 3.8 对私有方法的测试 ;
    1,修改方法的访问修饰符,讲private 修改 default或者 public ,但不推荐采取这种方式,因为测试尽量不去修改源代码;
    2 , 使用反射在测试类中调用目标类的私有方法;
 
源代码:
1 package com.study.junit;
2 
3 public class calculator {
4     
5     private int add(int a ,int b)
6     {
7         return a + b ;
8     }
9 }

测试代码:

 1 package com.study.junit;
 2 
 3 import java.lang.reflect.Method;
 4 
 5 import junit.framework.TestCase;
 6 
 7 public class calculatorTest extends TestCase {
 8     
 9    public void testadd()
10   {
11     try {
12      calculator cal = new calculator();
14      Class<calculator> clazz = calculator.class;
15      Method method = clazz.getDeclaredMethod("add", new Class[]{Integer.TYPE,Integer.TYPE});
16             
17      method.setAccessible(true);
18           
19     Object result = method.invoke(cal, new Object[]{2,3});
20             
21     assertEquals(5, result);
22     } catch (Exception e) {
23             
24     fail("测试失败");
25     }
26    }
27 }

 

posted @ 2012-05-08 22:12  广州_大臣  阅读(175)  评论(0编辑  收藏  举报