JUnit4中的测试套件

测试套件

  JUnit3.8中,用测试套件同时运行多个测试类(http://www.cnblogs.com/mengdd/archive/2013/04/07/3006265.html)。

  在JUnit4中也有类似功能,只不过是用注解来实现的。

Suite类的文档

public class Suite

extends org.junit.internal.runners.CompositeRunnerUsing

Suite as a runner allows you to manually build a suite containing tests from many classes.

It is the JUnit 4 equivalent of the JUnit 3.8.x static Test suite() method.

To use it, annotate a class with @RunWith(Suite.class) and @SuiteClasses(TestClass1.class, ...).

When you run this class, it will run all the tests in all the suite classes.

程序实例

   写一个类TestAll,然后让其运行CalculatorTest和ParametersTest中的测试:

package com.mengdd.junit4;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;

@RunWith(Suite.class)
// 指定运行器
@Suite.SuiteClasses({ CalculatorTest.class, ParametersTest.class })
// 指定要测试的类
public class TestAll
{

}

 另,在一个套件中也可包含另一个套件类,比如:

 再写一个类TestAll2,其中指定的类是上面的TestAll:

package com.mengdd.junit4;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses(TestAll.class)
// 除了指定类,也可以指定套件类
public class TestAll2
{

}

总结:

  在JUnit4中,如果想要同时运行多个测试类,需要使用两个注解:

  @RunWith(Suite.class)指定使用Suite运行器来运行测试;

  @SuiteClasses(ClassName.class)指定运行哪些测试类。测试类可以指定为Suite,这样JUnit会继续再去寻找里面的测试类,一直找到能够执行的Test Case并执行之。

参考资料

  圣思园张龙老师视频教程。

  JUnit4 chm格式文档网盘下载链接:

  JUnit 4.0:http://pan.baidu.com/share/link?shareid=539345&uk=2701745266

原文地址:https://www.cnblogs.com/huangcongcong/p/4749586.html