原文: https://howtodoinjava.com/junit5/junit-5-tag-annotation-example/
JUnit5 @Tag 可用于从测试计划中过滤测试用例。 它可以帮助针对不同的环境,不同的用例或任何特定要求创建多个不同的测试计划。 您可以通过仅在测试计划中包括那些标记的测试或通过从测试计划中排除其他测试来执行测试集。
1. @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 example@RunWith(JUnitPlatform.class)@SelectPackages("com.howtodoinjava.junit5.examples")@IncludeTags("production")public class MultipleTagsExample{}//@ExcludeTags example@RunWith(JUnitPlatform.class)@SelectPackages("com.howtodoinjava.junit5.examples")@ExcludeTags("production")public class MultipleTagsExample{}
要添加多个标签,请在所需注解中传递标签的字符串数组。
@RunWith(JUnitPlatform.class)@SelectPackages("com.howtodoinjava.junit5.examples")@IncludeTags({"production","development"})public class MultipleTagsExample{}
我们不能在单个测试计划中同时包含@IncludeTags和@ExcludeTags 注解。
3. JUnit5 @Tag示例
假设我们有 3 个测试,并且我们想在开发环境中运行全部 3 个测试; 但只想在生产中运行一个。 因此,我们将标记测试如下:
public class ClassATest{@Test@Tag("development")@Tag("production")void testCaseA(TestInfo testInfo) { //run in all environments}}public class ClassBTest{@Test@Tag("development")void testCaseB(TestInfo testInfo) {}}public class ClassCTest{@Test@Tag("development")void testCaseC(TestInfo testInfo) {}}
让我们为两种环境创建测试计划。
在生产环境中运行测试
@RunWith(JUnitPlatform.class)@SelectPackages("com.howtodoinjava.junit5.examples")@IncludeTags("production")public class ProductionTests{}

JUnit5 @Tag示例 – 生产测试
在开发环境中运行测试
@RunWith(JUnitPlatform.class)@SelectPackages("com.howtodoinjava.junit5.examples")@IncludeTags("development")public class DevelopmentTests{}

JUnit5 @Tag示例 – 开发测试
将我的问题放在评论部分。
学习愉快!
