修改Maven构建日志中"Time elapsed:"的时间格式
解决Maven测试时间格式逗号导致的XML解析错误
你的问题源于Maven Surefire插件生成的测试报告中,Time elapsed字段用逗号作为千位分隔符(比如3,289.634 s),而XML的decimal类型不允许数字中包含千位分隔符,因此触发cvc-datatype-valid.1.2.1解析错误。以下是几个实用的解决方案:
方案1:配置Surefire插件强制使用无千位分隔的数字格式
在pom.xml中给maven-surefire-plugin添加JVM参数,指定区域设置为美式格式(避免千位分隔符):
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.2.5</version> <!-- 替换为你当前使用的插件版本 --> <configuration> <argLine>-Duser.language=en -Duser.region=US</argLine> </configuration> </plugin> </plugins> </build>
配置后,测试时间会输出为3289.634 s,符合XML decimal类型的校验要求。
方案2:批量替换测试报告中的逗号
如果不想修改插件配置,可以在构建后通过脚本处理XML报告,移除时间字段中的逗号。借助exec-maven-plugin在post-build阶段执行shell命令:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.1.0</version> <executions> <execution> <phase>post-test</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>sed</executable> <arguments> <argument>-i</argument> <argument>'s/\([0-9]\),\([0-9]*\.\)/\1\2/g'</argument> <argument>target/surefire-reports/*.xml</argument> </arguments> </configuration> </execution> </executions> </plugin> </plugins> </build>
这个命令会遍历所有Surefire生成的XML文件,将数字中的逗号直接移除。
方案3:全局设置JVM区域
如果是本地开发环境或CI流水线,可以通过环境变量全局配置JVM区域,避免每次构建单独设置:
export JAVA_OPTS="-Duser.language=en -Duser.region=US"
设置后,所有Maven构建的测试时间输出都会采用无千位分隔的格式。
内容的提问来源于stack exchange,提问作者Sarayu
相关产品推荐
相关产品推荐

