You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Maven平台编码为US-ASCII而非UTF-8导致单元测试失败求助

解决Maven平台编码US-ASCII转UTF-8及Spring Boot测试编码异常问题

核心原因

系统默认编码或Maven启动的JVM编码优先级高于pom.xml配置,导致平台编码被强制设为US-ASCII,进而引发Spring Boot测试时的ApplicationContext加载异常。

解决方案

1. 配置系统环境变量(永久生效)

Linux/macOS

编辑shell配置文件(如~/.bashrc或~/.zshrc),添加以下内容:

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

执行以下命令使配置生效:

source ~/.bashrc  # 对应bash shell
# 或
source ~/.zshrc  # 对应zsh shell

Windows

打开「系统属性」→「高级」→「环境变量」,新建系统变量:

  • 变量名:LC_ALL,值:en_US.UTF-8
  • 变量名:LANG,值:en_US.UTF-8
    配置完成后重启命令行或IDE。

2. 修改Maven全局配置文件

找到Maven的settings.xml文件(通常路径为~/.m2/conf/settings.xml或Maven安装目录下的conf/settings.xml),添加以下配置:

<profiles>
    <profile>
        <id>utf8-encoding</id>
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        </properties>
    </profile>
</profiles>

<activeProfiles>
    <activeProfile>utf8-encoding</activeProfile>
</activeProfiles>

3. 命令行临时指定编码(快速测试)

运行Maven命令时直接附加JVM编码参数:

  • 验证编码:
    mvn -version -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
    
  • 运行测试:
    mvn test -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
    

4. IDE编码配置适配(如果用IDE运行测试)

IntelliJ IDEA

  • 打开File → Settings → Editor → File Encodings,将Global Encoding、Project Encoding、Default encoding for properties files全部设为UTF-8
  • 打开File → Settings → Build, Execution, Deployment → Build Tools → Maven → Runner,在VM options中添加:
    -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
    

Eclipse

  • 打开Window → Preferences → General → Workspace,设置Text file encoding为UTF-8
  • 打开Run → Run Configurations,找到对应的Maven Build配置,在VM arguments中添加:
    -Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8
    

内容的提问来源于stack exchange,提问作者Mitchel Abrahams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 05:42:18