首页 > 解决方案 > JUnit 5 测试套件选择测试方法

问题描述

有一些测试类Junit 5和 Spring Boot REST 控制器测试。

@SpringBootTest
@AutoConfigureMockMvc
public class TestClassA {
   @Autowired
   private MockMvc mockMvc;

   @Test
   @WithMockUser
   public void testMethod1() {
   ...
   }

   @Test
   @WithMockUser
   public void testMethod2() {
   ...
   }

   // more test methods
}

@SpringBootTest
@AutoConfigureMockMvc
public class TestClassB {
   @Autowired
   private MockMvc mockMvc;

   @Test
   @WithMockUser
   public void testMethod1() {
   ...
   }

   // more test methods

   @Test
   @WithMockUser
   public void testMethodX() {
      // requires that TestClassA.testMethod2()
      // must be run first
   }
}

测试类运行,每个测试一个特定的 REST 控制器,但是如何实现新的测试方法TestClassB.testMethodX()

我想在 JUnit 5 中创建一个测试套件并指定要运行的测试方法,也是按顺序:

1. run TestClassA.testMethod2()

2. run TestClassB.testMethodX()

我知道两个注释:@SelectPackages -@SelectClasses

但是无法选择特定的测试方法?这可以实现JUnit 5吗?

标签: spring-bootjunit5

解决方案


我不能回答你的两个问题,但至少我可以给你一个提示,告诉你如何选择一组应该运行的测试方法。

据我了解,单元/集成测试不应该依赖特定的顺序才能成功通过。真的有必要吗,或者您可以使用@Before注释之类的东西来实现任务的重要要求吗?

在我的设置中,我使用Gradle运行Spring Boot

JUnit 标签和过滤

JUnit 5 允许使用@Tag注解将标签添加到您的测试方法中。使用此功能,可以在测试执行时过滤您的测试方法。看看baeldung.com的简短教程。

标记您的测试方法

使用适合您目的的标签标记您的测试方法,如下所示。

   @Test
   @Tag("IntegrationTest")
   public void testMethod1() {
   ...
   }

   // more test methods

   @Test
   @Tag("UnitTest")
   public void testMethodX() {
   ...
   }

运行标记方法

使用 IntelliJ 运行标记方法

如果您使用 IntelliJ IDE,则使用特定标签运行测试方法相当简单。请参阅jetbrains.com 文档stackoverflow

  • Run-> Edit Configurations...-> +(添加新配置)->JUnit
  • 作为Test kinds选择Tags
  • Tag expression

智能

使用 Gradle 运行标记方法

如果您想在持续集成管道中运行测试方法,您可能会使用 Gradle 或 Maven 运行测试。对于 Gradle,我还可以向您展示使用特定标签运行方法的可能性。

对于build.gradle
依赖项,您可能已经集成了 JUnit 5 框架,类似于:

dependencies {
    // [...]
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
    // [...]
}

你也应该有一个test任务。

test {
    useJUnitPlatform()
}

该命令$ gradlew test现在将运行所有定义的测试方法。所以,要运行一组特定的方法,我建议创建自定义任务,就像这样。

test {
    useJUnitPlatform()
}

task unitTests(type: Test) {
    useJUnitPlatform {
        includeTags 'UnitTest'
    }
}

task integrationTests(type: Test) {
    useJUnitPlatform {
        includeTags 'IntegrationTest'
    }
}

之后,您可以在命令行界面上运行任务,例如:$ gradlew unitTests它只会运行您在自定义任务中定义的任务。


推荐阅读