对任何 Spring Boot 项目进行单元测试和集成测试。我想单独运行单元测试,而不会失去一次运行所有测试的能力。这个问题的解决方案:
- 默认从 IntelliJ 运行单元测试和集成测试,
- 支持从 cli 运行单元测试和集成测试的 Gradle 命令,并且
- 支持仅从 cli 运行单元测试的 Gradle 命令。完全忽略集成测试类很重要,因为它们包含构建环境中不可用的外部依赖项。
我的做法是在命令行通过测试配置文件:gradlew test -PtestProfile=unit
接下来,在 build.gradle
中,设置 Activity 的 spring 配置文件:
test {
if (project.hasProperty("testProfile")) {
systemProperty "spring.profiles.active", project.getProperties()["testProfile"]
}
}
问题:我如何注释我的集成测试类,以便每当 spring.profiles.active=unit
时,集成测试都会被跳过?
我试过:
@Profile
,在测试范围内不起作用,@IfProfile
,它不适用于场景 1,因为它需要传递一个显式属性。@ActiveProfiles
,它不起作用,因为它会覆盖当前 Activity 的配置文件,而不是有条件地禁用测试。
正确的做法是什么?
最佳答案
感谢@JBNizet,以下解决方案适用于我。
我们还是在命令行通过一个测试配置文件:
gradlew 测试 -PtestProfile=unit
在build.gradle
中,我们设置了一个excludeCategory
:
test {
if (project.hasProperty("testProfile")) {
if (project.getProperties()["testProfile"] == "unit") {
useJUnit {
excludeCategories "com.yourproject.testutils.IntegrationTestCategory"
}
}
}
}
添加一个空接口(interface)com.yourproject.testutils.IntegrationTestCategory
。在您希望排除的测试类上,添加注释 @Category(IntegrationTestCategory.class)
。
您的测试现在默认启用,但可以通过 Gradle cli 选择性地忽略。
关于java - 忽略基于 Spring Boot 配置文件的测试类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57448710/