junit3.8

1. 使用Junit的最佳实践:
1) 新建一个名为test的source folder,用于存放测试类源代码
2) 目标类与测试类应该位于同一个包下面,这样测试类中就不必导入源代码所在的包,因为他们位于同一个包下面
3) 测试类的命名规则:假如目标类是Calculator,那么测试类应该命名为TestCalculator或者是CalculatorTest

在junit 3.8中,测试类必须要继承于TestCase父类。测试方法需要满足如下原则:
1). public的
2). void的
3). 无方法参数
4). 方法名称必须以test开头

Test Case之间一定要保持完全的独立性,不允许出现任何的依赖关系。即这个测试方法绝对不允许依赖于另外一个测试方法

我们不能依赖于测试方法的执行顺序,因为它是按照组合模式排队执行的.

关于setUp与tearDown方法的执行顺序:
1) setUp
2) testAdd
3) tearDown

 

除了eclipse提供的junit之外,还可以独立的用junit的运行器,但是要放在main方法中,其实eclipse中也

是有一个main方法的,给我们隐藏了而已:

在main方法如何测试:

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

 在测试类中加入main方法 :junit.textui.TestRunner.run(Caculator.class);//文本界面
junit.awtui.TestRunner.run(Caculator.class);//图形界面

 

如何测试私有方法:

测试类的私有方法时可以采取两种方式:
1) 修改方法的访问修饰符,将private修改为default或public(但不推荐采取这种方式)。
2) 使用反射在测试类中调用目标类的私有方法(推荐)。

public class Caculator2Test extends TestCase{
 public void testAdd(){
  Caculator2 caculator2=new Caculator2();
  Class clazz=Caculator2.class;
  try {
   Method method=clazz.getDeclaredMethod("add",new Class[]{Integer.TYPE,Integer.TYPE});
   method.setAccessible(true);//设置可访问
   Object result=method.invoke(caculator2,new Object[]{2,3});
   Assert.assertEquals(5,result);
  } catch(Exception e){
   Assert.fail();
  }
 }
}

异常处理:

public void testGetLargest2(){
  Throwable tx=null;
  int[] array=null;
  int result=0;
  try {
   result=ma.getLargest(array);
   Assert.fail();//我们的预期是不应该执行到这里,如果会执行到这里表明测试失败,Assert.fail()是放在不会执行到的地方的
  } catch (Exception e) {
   tx=e;
  }
  Assert.assertNotNull(tx);
  Assert.assertEquals(Exception.class,tx.getClass());
  Assert.assertEquals("数组不能为空或数组长度不能为0",tx.getMessage());
 }

测试套件:TestSuite

public class TestAll extends TestCase{
 public static Test suite(){//这里是有固定的写法的,public static Test的,方法名为suite
  TestSuite suite=new TestSuite();
  suite.addTestSuite(CaculatorTest.class);
  suite.addTestSuite(DeleteAllTest.class);
  
  suite.addTest(new RepeatedTest(new CaculatorTest("testAdd"),100000));//RepeatedTest:重复测试,让哪个方法重复执行多少次,在这里让CaculatorTest这个测试类中的substract方法重复执行20次
  
  return suite;
 }
}

 

重要的一点就是测试之前的状态和测试之后的状态应该是一致的,如测试数据库,那么你要先自己insert进去数据,然后测试,最后要注意在tearDowm方法当中你应该把这个插入的数据再清掉.让数据库里面的东西保持原样!又如删除目录的测试,那么也是这样,自己在setUp中建立目录,最后在tearDown当中又把目录全部删除干净.

一个测试用例就是一个测试方法嘛.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yjsuge

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值