JUnit 4 超详细教程(二)
上篇文档地址:JUnit 4 超详细教程(一)
1.在套件中聚合测试
使用“Suite”作为运行程序,可以手动构建包含来自多个类的测试的套件。它是JUnit4与JUnit3.8.xstatic Test suite()
方法的等价物。
要使用它,请使用@RunWith(Suite.class)
和`@SuiteClasses(TestClass1.class,…)注释一个类。运行此类时,它将运行所有套件类中的所有测试。
下面的类是套件注释的占位符,不需要其他实现。请注意@RunWith
注释,它指定用于运行此特定测试类的JUnit4测试运行程序为org.JUnit.runners.Suite
。这与@Suite.SuiteClasses
注释一起工作,该注释告诉套件运行者此套件中要包含哪些测试类以及测试类的顺序。
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
TestFeatureLogin.class,
TestFeatureLogout.class,
TestFeatureNavigate.class,
TestFeatureUpdate.class
})
public class FeatureTestSuite {
// the class remains empty,
// used only as a holder for the above annotations
}
2.分类
从给定的一组测试类中,“分类”运行程序只运行使用“@IncludeCategory”注释给定的类别或该类别的子类型进行注释的类和方法。类或接口都可以用作类别。
子类型工作,因此如果使用“@IncludeCategory(SuperClass.class)”,则将运行标记为“@Category({SubClass.class})”的测试。
还可以使用“@ExcludeCategory”注释排除类别。
public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }
public class A {
@Test
public void a() {
fail();
}
@Category(SlowTests.class)
@Test
public void b() {
}
}
@Category({SlowTests.class, FastTests.class})
public class B {
@Test
public void c() {
}
}
@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
// Will run A.b and B.c, but not A.a
}
@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses( { A.class, B.class }) // Note that Categories is a kind of Suite
public class SlowTestSuite {
// Will run A.b, but not A.a or B.c
}
2.1.在Maven中使用分类
您可以将分类与[maven surefire plugin]一起使用(http://maven.apache.org/surefire/maven-surefire-plugin/examples/junit.html)(用于单元测试)或maven故障保护插件(用于集成测试)。使用任一插件,您都可以配置要包括或排除的类别列表。如果不使用任何一个选项,默认情况下将执行所有测试。
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<groups>com.example.FastTests,com.example.RegressionTests</groups>
</configuration>
</plugin>
</plugins>
</build>
类似地,要排除某个类别列表,可以使用<excludedGroups/>
配置元素。
2.2.在Gradle中使用分类
Gradle的测试任务允许指定要包括和排除的JUnit类别。
test {
useJUnit {
includeCategories 'org.gradle.junit.CategoryA'
excludeCategories 'org.gradle.junit.CategoryB'
}
}
2.3.分类的典型用法
类别用于在测试中添加元数据。
常见的类别用法有:
-自动测试的类型:单元测试、集成测试、冒烟测试、回归测试、性能测试。。。
-测试执行的速度:慢测试,快测试
-应在ci构建的哪个部分执行测试:夜间构建测试
-测试状态:不稳定测试、程序内测试
这还用于添加特定于项目的元数据,例如测试涵盖了项目的哪个功能。