Eclipse中使用junit测试私有方法

     写了一个简单的测试私有方法的代码,希望能够对学习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;
 }
}


 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值