配置maven-surefire-report-plugin读取多源测试报告目录
解决maven-surefire-report-plugin读取多fork测试报告的问题
首先,你遇到的问题根源是:maven-surefire-report-plugin的reportsDirectories参数不支持通配符匹配,所以直接配置<reportsDirectory>target/surefire-reports*</reportsDirectory>不会被插件解析,自然读不到任何测试数据。
下面给你两种可行的解决方案,分别适用于灵活环境和固定环境:
方案一:动态收集所有fork报告目录(推荐)
我们可以借助build-helper-maven-plugin在构建前自动扫描并收集所有target/surefire-reports-*格式的目录,再把这些目录传递给maven-surefire-report-plugin。
步骤1:添加build-helper-maven-plugin配置
这个插件会在pre-site阶段(生成站点报告前)扫描目标目录,把所有匹配的测试报告目录整理成逗号分隔的列表:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>collect-surefire-report-dirs</id> <phase>pre-site</phase> <goals> <goal>regex-property</goal> </goals> <configuration> <name>surefire.report.dirs</name> <files> <directory>${project.build.directory}</directory> <includes> <include>surefire-reports-*</include> </includes> </files> <pathSeparator>,</pathSeparator> </configuration> </execution> </executions> </plugin>
步骤2:配置maven-surefire-report-plugin使用收集到的目录
把上面生成的${surefire.report.dirs}属性传入插件的reportsDirectories:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>3.0.0-M7</version> <configuration> <reportsDirectories> <reportsDirectory>${surefire.report.dirs}</reportsDirectory> </reportsDirectories> </configuration> <!-- 确保插件在测试完成后执行 --> <executions> <execution> <phase>site</phase> <goals> <goal>report</goal> </goals> </execution> </executions> </plugin>
方案二:固定列出所有可能的fork目录(适合环境固定的场景)
如果你的构建机器核心数固定,或者forkCount设置的是固定数值而非相对值(比如forkCount=3而不是3C),可以直接显式列出所有可能的报告目录:
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>3.0.0-M7</version> <configuration> <reportsDirectories> <reportsDirectory>target/surefire-reports-1</reportsDirectory> <reportsDirectory>target/surefire-reports-2</reportsDirectory> <reportsDirectory>target/surefire-reports-3</reportsDirectory> <!-- 根据你的fork数量继续添加到最大值 --> </reportsDirectories> </configuration> </plugin>
这个方法的缺点是不够灵活,一旦机器核心数变化或者fork数量调整,就需要手动更新配置。
最后提醒:确保maven-surefire-report-plugin的执行阶段在maven-surefire-plugin之后(比如默认的site阶段),这样所有测试报告都已经生成完毕,插件才能正确读取。
内容的提问来源于stack exchange,提问作者stwissel
相关产品推荐
相关产品推荐

