文
章
目
录
章
目
录
JUnit 5 的 @Tag 注解可以用于从测试套件中筛选测试用例。它可以帮助我们针对不同的环境、不同的用例或任何特定需求创建多个不同的测试套件。
我们可以仅将包含特定标记的测试用例包含在测试计划中,或者将其他测试用例从测试计划中排除。
1.@Tag 的使用
我们可以将 @Tag 注解应用于测试类、测试方法或同时应用于两者。
@Tag("development")
public class ClassATest
{
@Test
@Tag("userManagement")
void testCaseA(TestInfo testInfo) {
}
}
我们还可以在单个测试用例上应用多个标签,以便将测试用例包含在多个测试套件中。
public class ClassATest
{
@Test
@Tag("development")
@Tag("production")
void testCaseA(TestInfo testInfo) {
}
}
2.使用 @IncludeTags 和 @ExcludeTags 创建套件
我们可以在套件中使用 @IncludeTags 或 @ExcludeTags 注解来筛选测试用例或包含测试用例。
//@IncludeTags示例
@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("production")
public class MultipleTagsExample
{
}
//@ExcludeTags 示例
@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@ExcludeTags("production")
public class MultipleTagsExample
{
}
要将多个标签添加到所需注解中,请传递一个字符串数组。
@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags({"production","development"})
public class MultipleTagsExample
{
}
注意:我们不能在同一个测试套件中同时包含 @IncludeTags 和 @ExcludeTags 注解。
3.JUnit 5 @Tag 示例
假设我们有三个测试,我们想在开发环境中运行这三个测试,但在生产环境中只运行一个。因此,我们将以下标记应用于测试:
public class ClassATest
{
@Test
@Tag("development")
@Tag("production")
void testCaseA(TestInfo testInfo) { //运行所有环境
}
}
public class ClassBTest
{
@Test
@Tag("development")
void testCaseB(TestInfo testInfo) {
}
}
public class ClassCTest
{
@Test
@Tag("development")
void testCaseC(TestInfo testInfo) {
}
}
创建两个测试套件,一个用于每个环境。
要在生产环境中运行的测试:
@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("production")
public class ProductionTests
{
}
要在开发环境中运行的测试:
@Suite
@SelectPackages("com.howtodoinjava.junit5.examples")
@IncludeTags("development")
public class DevelopmentTests
{
}