
Windows 10 环境中 Maven 执行测试时出现乱码(如“Текст”),导致含非拉丁字符的断言失败,而 IDEA 内运行正常——根本原因是 Maven Surefire 插件默认未显式指定 UTF-8 编码,需在 pom.xml 中配置 maven-surefire-plugin 的 encoding 参数。
windows 10 环境中 maven 执行测试时出现乱码(如“Текст”),导致含非拉丁字符的断言失败,而 idea 内运行正常——根本原因是 maven surefire 插件默认未显式指定 utf-8 编码,需在 `pom.xml` 中配置 `maven-surefire-plugin` 的 `encoding` 参数。
在 Spring Boot + Maven 项目中,Windows 系统默认控制台编码通常为 GBK 或 CP1251,而 Java 源文件、资源文件及测试数据若使用 UTF-8 编码(尤其含中文、俄文等非 ASCII 字符),Maven 默认启动的测试进程(通过 maven-surefire-plugin)并不会自动继承 project.build.sourceEncoding 的值来设置 JVM 输出/读取编码,从而导致字符串比较失败。
虽然你已配置了:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties>
并尝试通过 <argLine>-Dfile.encoding=UTF-8</argLine> 设置 JVM 参数,但 -Dfile.encoding 仅影响 FileReader/FileWriter 等基于默认平台编码的 API,不保证 System.out、String.getBytes() 或 InputStreamReader 在无显式指定时的行为一致;更重要的是,maven-surefire-plugin 自 2.22.0 起已弃用 encoding 属性(该属性曾用于报告生成),真正影响测试执行期字符串处理的关键配置是 argLine 中的 -Dfile.encoding=UTF-8 ——但必须确保它被正确传递且优先级足够高。
✅ 正确且兼容性最佳的解决方案是:显式声明并配置 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>-Dfile.encoding=UTF-8</argLine>
<!-- 可选:强制系统属性生效,增强兼容性 -->
<systemPropertyVariables>
<file.encoding>UTF-8</file.encoding>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>⚠️ 注意事项:
- 若项目中未声明 maven-surefire-plugin,Maven 会使用内置版本(可能较旧),建议显式声明并指定较新版本(≥2.22.0),以避免已知编码相关 Bug;
- Windows 命令行(CMD/PowerShell)本身对 UTF-8 支持有限,推荐在 IDE 或 Git Bash / Windows Terminal(启用 UTF-8)中运行 mvn test;也可临时在 CMD 中执行 chcp 65001 切换到 UTF-8 代码页(但非持久化方案);
- 确保 .java 源文件、application.properties/yml、测试资源文件(如 test-data.txt)本身以 UTF-8 无 BOM 格式保存;
- 若使用 @SpringBootTest 并加载含非 ASCII 字符的配置项,还需确认 spring.config.encoding=UTF-8(Spring Boot 2.4+ 默认启用,低版本需显式配置)。
完成配置后,执行 mvn clean test,测试应能稳定通过。该方案兼顾可移植性与确定性,是 Maven 多语言环境下的标准实践。


















