原文: https://howtodoinjava.com/junit5/junit-5-tag-annotation-example/

JUnit5 @Tag 可用于从测试计划中过滤测试用例。 它可以帮助针对不同的环境,不同的用例或任何特定要求创建多个不同的测试计划。 您可以通过仅在测试计划中包括那些标记的测试或通过从测试计划中排除其他测试来执行测试集。

1. @Tag注解用法

  1. 我们可以将其应用于测试类或测试方法或同时应用
    1. @Tag("development")
    2. public class ClassATest
    3. {
    4. @Test
    5. @Tag("userManagement")
    6. void testCaseA(TestInfo testInfo) {
    7. }
    8. }
  1. 我们也可以将多个标签应用于单个测试案例,以便您可以将其包含在多个测试计划中。
    1. public class ClassATest
    2. {
    3. @Test
    4. @Tag("development")
    5. @Tag("production")
    6. void testCaseA(TestInfo testInfo) {
    7. }
    8. }

2. 使用@IncludeTags@ExcludeTags创建测试计划

我们可以在测试计划中使用@IncludeTags@ExcludeTags注解来过滤测试或包括测试。

  1. //@IncludeTags example
  2. @RunWith(JUnitPlatform.class)
  3. @SelectPackages("com.howtodoinjava.junit5.examples")
  4. @IncludeTags("production")
  5. public class MultipleTagsExample
  6. {
  7. }
  8. //@ExcludeTags example
  9. @RunWith(JUnitPlatform.class)
  10. @SelectPackages("com.howtodoinjava.junit5.examples")
  11. @ExcludeTags("production")
  12. public class MultipleTagsExample
  13. {
  14. }

要添加多个标签,请在所需注解中传递标签的字符串数组

  1. @RunWith(JUnitPlatform.class)
  2. @SelectPackages("com.howtodoinjava.junit5.examples")
  3. @IncludeTags({"production","development"})
  4. public class MultipleTagsExample
  5. {
  6. }

我们不能在单个测试计划中同时包含@IncludeTags@ExcludeTags 注解。

3. JUnit5 @Tag示例

假设我们有 3 个测试,并且我们想在开发环境中运行全部 3 个测试; 但只想在生产中运行一个。 因此,我们将标记测试如下:

  1. public class ClassATest
  2. {
  3. @Test
  4. @Tag("development")
  5. @Tag("production")
  6. void testCaseA(TestInfo testInfo) { //run in all environments
  7. }
  8. }
  9. public class ClassBTest
  10. {
  11. @Test
  12. @Tag("development")
  13. void testCaseB(TestInfo testInfo) {
  14. }
  15. }
  16. public class ClassCTest
  17. {
  18. @Test
  19. @Tag("development")
  20. void testCaseC(TestInfo testInfo) {
  21. }
  22. }

让我们为两种环境创建测试计划。

在生产环境中运行测试

  1. @RunWith(JUnitPlatform.class)
  2. @SelectPackages("com.howtodoinjava.junit5.examples")
  3. @IncludeTags("production")
  4. public class ProductionTests
  5. {
  6. }

JUnit5 `@Tag`注解示例 - 图1

JUnit5 @Tag示例 – 生产测试

在开发环境中运行测试

  1. @RunWith(JUnitPlatform.class)
  2. @SelectPackages("com.howtodoinjava.junit5.examples")
  3. @IncludeTags("development")
  4. public class DevelopmentTests
  5. {
  6. }

JUnit5 `@Tag`注解示例 - 图2

JUnit5 @Tag示例 – 开发测试

将我的问题放在评论部分。

学习愉快!

源码下载