spring-boot - 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
吗?
解决方案
我不能回答你的两个问题,但至少我可以给你一个提示,告诉你如何选择一组应该运行的测试方法。
据我了解,单元/集成测试不应该依赖特定的顺序才能成功通过。真的有必要吗,或者您可以使用@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
它只会运行您在自定义任务中定义的任务。
推荐阅读
- python - 最受欢迎的嵌套类别
- linux - 如何为我的 AMD Linux 系统构建 Tensorflow?
- azure-devops - 阻止 azure 管道运行我的模板文件
- c# - 是否可以在不启用子属性隐式验证的情况下使用 FluentValidation 验证可枚举模型?
- java - Java IO 控制台
- angular - 为什么角度在spring boot api中的日期变量中发送空值
- css-grid - 交互式复制中的 CSS Grid 意外分布
- swift - 在 SwiftUI 中呈现没有动画的弹出框
- reactjs - 如何在 React 中访问嵌套数组对象
- javascript - 如何从频道用户名中获取 YouTube 频道 ID