写了一个简单的测试私有方法的代码,希望能够对学习junit的人有帮助~
被测程序源码:
package code;
public class Car {
private String owner;
private int wheels=4;
public Car()
{}
public int getWheels()
{
//返回当前车辆的车轮数
return this.wheels;
}
//获取车辆所有者的方法是私有的
private String getOwner(String owner)
{
if(owner.equals("1"))
this.owner="helen";
else
this.owner="unknown";
return this.owner;
}
}
测试代码:
package junit;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import junit.framework.*;
import code.*;
public class TestCar extends TestCase {
public Car car;
public int expectedWheels;
public String expectedOwner;
//构造方法,以便将test 组合成testsuite
public TestCar(String name)
{
super(name);
}
protected void setUp() throws Exception {
car=new Car();
expectedWheels=4;
expectedOwner="helen";
}
//此测试方法测试公有的getWheels方法
public void testGetWheels() {
assertEquals("wrong wheels",expectedWheels,car.getWheels());
}
//利用反射机制测试私有方法
public void testGetOwner()
{
try {
Method m=car.getClass().getDeclaredMethod("getOwner", new Class[]{String.class});
m.setAccessible(true); //true时不进行java语言访问检查
String real=(String)m.invoke(car, new Object[]{new String("1")});
m.setAccessible(false); //false时进行检查
assertEquals("should be ",expectedOwner,real);
}catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Test suite()
{
//创建测试集
TestSuite s=new TestSuite("TestCar");
s.addTest(new TestCar("testGetWheels"));
s.addTest(new TestCar("testGetOwner"));
return s;
}
}