JaCoCo Maven插件配置生成XML格式覆盖率报告报错排查
报错根因
- 直接触发报错的原因是
formats参数是java.util.List类型,直接在<formats>标签内写入XML字符串时,Maven会把这个值识别为单个字符串类型,和要求的列表类型不匹配,无法完成类型转换。 - 配置位置错误:
formats写在了插件全局<configuration>层级,这个参数只有report、report-aggregate两个生成报告的goal支持,prepare-agent、merge等其他goal不识别该参数,全局配置不仅不会生效,还会干扰其他goal的参数解析。 - 版本不匹配:
formats自定义输出格式的配置是JaCoCo Maven Plugin 0.8.8版本才新增的特性,你提到自己使用0.8.7版本,但报错信息显示实际运行的插件版本是0.8.8,版本混用也会导致配置异常。
调整方案
根据你使用的插件版本二选一即可:
方案1:使用0.8.8及以上版本(推荐,可自定义输出格式)
- 先统一插件版本,将
${jacoco-maven-plugin.version}的值明确设置为0.8.8及以上稳定版(目前最新稳定版为0.8.12),避免版本混用。 - 删除插件全局层级的
<formats>配置,将格式配置移动到report和report-aggregate两个goal的独立<configuration>块中。 - 修正
formats的写法,用<format>子标签包裹每个需要的输出格式,支持的格式取值为XML、HTML、CSV,需要多个格式就新增多个<format>标签。
调整后的核心配置示例如下:
<plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> <version>0.8.12</version> <executions> <execution> <id>jacoco-initialize-unit-test</id> <goals> <goal>prepare-agent</goal> <goal>report</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/../target/site/jacoco-aggregate</outputDirectory> <append>true</append> <propertyName>jacoco.agent.argLine</propertyName> <!-- 单元测试报告输出格式配置 --> <formats> <format>XML</format> <!-- 需要其他格式可按需添加,不需要就删除对应行 --> <format>HTML</format> <format>CSV</format> </formats> </configuration> </execution> <execution> <id>jacoco-initialize-integration-test</id> <phase>pre-integration-test</phase> <goals> <goal>prepare-agent</goal> </goals> <configuration> <destFile>${project.build.directory}/../../target/coverage-reports/jacoco-it.exec</destFile> <append>true</append> <propertyName>jacoco.agent.argLine</propertyName> </configuration> </execution> <execution> <id>jacoco-merge</id> <phase>post-integration-test</phase> <goals> <goal>merge</goal> </goals> <configuration> <fileSets> <fileset> <directory>${project.build.directory}/../../target/coverage-reports/</directory> <includes> <include>*.exec</include> </includes> </fileset> </fileSets> <destFile>${project.build.directory}/../../target/coverage-reports/jacoco.exec</destFile> </configuration> </execution> <execution> <id>jacoco-report</id> <phase>verify</phase> <goals> <goal>report-aggregate</goal> </goals> <configuration> <outputDirectory>${project.build.directory}/../target/site/jacoco-aggregate</outputDirectory> <!-- 聚合报告输出格式配置 --> <formats> <format>XML</format> <format>HTML</format> </formats> </configuration> </execution> </executions> </plugin>
方案2:继续使用0.8.7版本
0.8.7版本没有开放formats自定义配置项,执行报告生成goal时默认会同时输出HTML、XML、CSV三种格式的报告,你只需要把之前在全局configuration里加的<formats>XML</formats>配置完全删除即可,不需要额外加其他格式相关配置。
验证方法
配置调整完成后,执行mvn clean verify命令跑全量构建,构建成功后到你配置的输出目录target/site/jacoco-aggregate下,就能找到生成的jacoco.xml文件,不会再出现类型转换报错。
内容的提问来源于stack exchange,提问作者Scientist
相关产品推荐
相关产品推荐

