纯JUnit 5项目配置测试套件后Maven排除规则不生效如何解决
排除规则不生效的核心原因
- Maven Surefire插件的匹配规则默认针对编译后的
.class测试类,你配置的**/*TestSuite.java匹配的是Java源文件,无法匹配编译后的类文件,因此排除规则无法命中目标类。 - 多规则配置格式错误:你在同一个
<include>标签中用逗号分隔多个匹配规则,低版本Surefire插件不识别这种写法,会导致包含规则失效,连带排除规则的优先级也受影响。 - 包排除规则格式不符合要求:直接写点分隔的包名
my.project.domain.testsuite不符合Surefire的路径匹配规则,需要用斜杠分隔的路径格式搭配通配符才能命中指定包下的所有类。 - 死循环的根本原因:测试套件配置的
@SelectPackages("my.project.domain")包含了测试套件自身所在的包,JUnit Platform扫描时会反复识别到测试套件类,递归执行套件逻辑形成死循环,重复执行的测试用例也会因此出现执行失败。
解决方案
1. 修正Surefire插件配置
升级到最新稳定版Surefire插件,同时调整包含/排除规则的写法:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.2</version> <configuration> <skip>false</skip> <excludes> <exclude>**/*TestSuite.class</exclude> <exclude>**/my/project/domain/testsuite/**/*</exclude> </excludes> <includes> <include>**/*Test.class</include> <include>**/*IT.class</include> </includes> </configuration> </plugin>
2. 避免测试套件递归扫描
如果需要保留测试套件类不被排除,可以在套件注解中添加排除自身所在包的配置:
import org.junit.platform.runner.JUnitPlatform; import org.junit.platform.suite.api.ExcludePackages; import org.junit.platform.suite.api.IncludeTags; import org.junit.platform.suite.api.SelectPackages; import org.junit.runner.RunWith; @RunWith(JUnitPlatform.class) @SelectPackages("my.project.domain") @ExcludePackages("my.project.domain.testsuite") @IncludeTags("long-running-test") public interface LongRunningTestSuite {}
3. 纯JUnit5项目使用原生套件(推荐)
无需兼容JUnit4的场景下,直接使用JUnit5原生套件能力,避免跨版本适配问题,需要先引入JUnit5套件依赖:
<dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-suite-api</artifactId> <version>1.10.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-suite-engine</artifactId> <version>1.10.0</version> <scope>test</scope> </dependency>
对应的套件代码简化为:
import org.junit.platform.suite.api.IncludeTags; import org.junit.platform.suite.api.SelectPackages; import org.junit.platform.suite.api.Suite; @Suite @SelectPackages("my.project.domain") @IncludeTags("long-running-test") public class LongRunningTestSuite {}
内容的提问来源于stack exchange,提问作者myborobudur
相关产品推荐
相关产品推荐

