JUnit中的测试套件和参数化测试

发表于:2014-12-17 10:48

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:玄玉    来源:51Testing软件测试网采编

  JUnit4.x的测试运行器
  JUnit单元测试提供了默认的测试运行器,它的测试方法都是由它负责执行的
  我们也可以定制自己的运行器,所有的运行器都继承自org.junit.runner.Runner
  还可以使用org.junit.runer.RunWith注解 为每个测试类指定使用具体的运行器
  一般情况下,默认测试运行器可以应对绝大多数的单元测试要求
  当使用JUnit提供的一些高级特性,或者针对特殊需求定制JUnit测试方式时
  显式的声明测试运行就必不可少了
  JUnit4.x测试套件的创建步骤
  ① 创建一个空类作为测试套件的入口
  ② 使用org.junit.runner.RunWith 和org.junit.runners.Suite.SuiteClasses注解 修饰该空类
  ③ 将org.junit.runners.Suite 作为参数传入RunWith注解,即使用套件运行器执行此类
  ④ 将需要放入此测试套件的测试类组成数组,作为SuiteClasses注解的参数
  ⑤ 保证这个空类使用public 修饰,而且存在公开的不带有任何参数的构造函数
  下面是JUnit4.x中创建测试套件类的示例代码
package com.jadyer.junit4;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* JUnit4.x测试套件的举例
* @see 下面的CalculatorTest.class和ParameterTest.class均为我们自己编写的JUnit4单元测试类
*/
@RunWith(Suite.class)
@SuiteClasses({CalculatorTest.class, ParameterTest.class})
public class TestAll {}
  下面是JUnit3.8中创建测试套件类的示例代码
package com.jadyer.junit3;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* JUnit3.8中批量运行所有的测试类。。直接在该类上Run As JUnit Test即可
* @see 这里就用到了设计模式中典型的组合模式,即将不同的东西组合起来
* @see 组合之后的东西,即可以包含本身,又可以包含组成它的某一部分
* @see TestSuite本身是由TestCase来组成的,那么TestSuite里面就可以包含TestCase
* @see 同时TestSuite里面还可以继续包含TestSuite,形成一种递归的关系
* @see 这里就体现出来了,所以这是一种非常非常好的设计模式,一种好的策略
*/
public class TestAll extends TestCase {
//方法名固定的,必须为public static Test suite()
public static Test suite() {
//TestSuite类实现了Test接口
TestSuite suite = new TestSuite();
//这里传递的是测试类的Class对象。该方法还可以接收TestSuite类型对象
suite.addTestSuite(CalculatorTest.class);
suite.addTestSuite(MyStackTest.class);
return suite;
}
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号