
Windows 10 默认使用 GBK 编码,而 Spring Boot 项目常依赖 UTF-8 处理非拉丁字符(如俄文、中文),导致 mvn test 时字符串乱码(如 "Текст"),但在 IntelliJ IDEA 中正常——根本原因是 Maven Surefire 插件未显式指定测试执行编码。
windows 10 默认使用 gbk 编码,而 spring boot 项目常依赖 utf-8 处理非拉丁字符(如俄文、中文),导致 `mvn test` 时字符串乱码(如 "Текст"),但在 intellij idea 中正常——根本原因是 maven surefire 插件未显式指定测试执行编码。
在 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>
以及尝试通过 -Dfile.encoding=UTF-8 设置 JVM 参数,仍可能因 Windows 控制台、PowerShell 或 CMD 的终端编码限制,或 Surefire 插件自身对测试类加载/标准输出流的编码处理不一致,导致 String 断言失败。
✅ 正确且最直接的解决方案是:为 maven-surefire-plugin 显式声明 <encoding>UTF-8</encoding>,并确保其 <argLine> 包含 -Dfile.encoding=UTF-8(双重保障)。
通过 SSH 隧道从 Android 设备在互联网上对 Windows PC 实现完整远程控制的设置与使用指南,适用于远程桌面访问、安全 RDP 等。
在 pom.xml 的 <build><plugins> 中添加或更新 Surefire 插件配置(推荐使用最新稳定版,如 3.2.5):
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
<configuration>
<encoding>UTF-8</encoding>
<argLine>-Dfile.encoding=UTF-8</argLine>
<!-- 可选:强制 JVM 使用 UTF-8 输出(避免控制台截断) -->
<systemPropertyVariables>
<file.encoding>UTF-8</file.encoding>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>⚠️ 注意事项:
- 版本兼容性:Spring Boot 3.x 推荐使用 Surefire ≥ 3.0.0;若用旧版 Spring Boot 2.x,2.22.2 或 3.0.0-M9 以上亦可。
- IDE 同步:IntelliJ 默认使用项目编码运行测试,且会自动注入 -Dfile.encoding=UTF-8,因此本地 IDE 运行无问题——但 CI/CD 或命令行 mvn test 必须依赖此插件配置。
- 额外加固(Windows 环境):若仍出现控制台乱码(非测试失败,仅日志显示异常),可在运行前执行 chcp 65001(切换当前 CMD/PowerShell 为 UTF-8 模式),或在 CI 脚本中前置该命令。
- 验证方式:添加一个简单测试验证编码是否生效:
@Test
void testUtf8String() {
String expected = "Текст"; // 俄文示例
String actual = new String("Текст".getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
assertEquals(expected, actual); // 应通过
}总结:<project.build.sourceEncoding> 仅影响源码编译阶段,而测试执行阶段由 Surefire 控制。显式配置 Surefire 的 <encoding> 和 <argLine> 是跨平台(尤其 Windows)保障 UTF-8 字符正确解析与比较的必要实践。

















