您的位置:首页 > 其它

Junit3.X 初学 (四) 如何测试类的静态Static方法

2014-03-31 21:23 281 查看
如何测试类的静态Static方法?

a)将private方法的访问符改为 default (因为default访问修饰符课在同一个包中访问)

b) 用反射机制 method.getDeclaredMethod() 

待测试类:

package com.sysu.junit3;

public class PrivateCalculator {

private int add(int a,int b)
{
return a+b;
}

}

测试类:
package com.sysu.junit3;

import java.lang.reflect.Method;

import junit.framework.Assert;
import junit.framework.TestCase;

public class PrivateCalculatorTest extends TestCase {

private PrivateCalculator calculator = null;

@Override
protected void setUp() throws Exception {
calculator = new PrivateCalculator();
}

public void testAdd() {

try {
Class<PrivateCalculator> classtype = PrivateCalculator.class;
Method method = classtype.getDeclaredMethod("add", new Class[] {
Integer.TYPE, int.class }); //用反射机制 method.getDeclaredMethod() 
method.setAccessible(true); //设置 为true ,关闭JVM对访问规则的遵守。

Integer sum = null;

sum = (Integer) method.invoke(calculator, new Object[] {
new Integer(19), 81 });
Assert.assertNotNull(sum);
Assert.assertEquals(new Integer(100), sum);
} catch (Exception ex) {
ex.printStackTrace();
Assert.fail();
}

}

public static void main(String[] args) {
junit.awtui.TestRunner.run(PrivateCalculatorTest.class);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: