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

IntelliJ运行测试正常切换为Gradle运行失败的原因及解决方法

问题原因
  • 核心触发点为SimpleDateFormat实例化时未显式指定Locale,默认会继承当前JVM运行环境的系统Locale
  • IntelliJ默认运行测试时的JVM Locale为英文环境,可以正常识别Dec这类英文月份缩写,因此解析成功
  • Gradle运行测试时JVM会优先使用操作系统默认Locale,例如中文系统下默认Locale为zh-CN,对应月份缩写格式为12月而非Dec,因此无法匹配输入的日期字符串,抛出ParseException
解决方案

提供两种修复路径,可根据场景选择:

方案1:代码层面显式指定Locale(最推荐,无环境依赖)

在实例化SimpleDateFormat时传入英文Locale,保证日期解析逻辑和运行环境解耦:

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy", Locale.ENGLISH);

String d1s = "11-Dec-2021";
String d2s = "12-Dec-2021";
Date d1 = formatter.parse(d1s);
Date d2 = formatter.parse(d2s);

如果使用Java 8及以上版本,更推荐使用线程安全的DateTimeFormatter替代SimpleDateFormat:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MMM-yyyy", Locale.ENGLISH);
LocalDate d1 = LocalDate.parse("11-Dec-2021", formatter);
LocalDate d2 = LocalDate.parse("12-Dec-2021", formatter);

方案2:不修改代码,统一Gradle测试运行的JVM Locale

在项目的build.gradle文件中新增test块的JVM参数配置,强制Gradle运行测试时使用英文Locale:

test {
    jvmArgs '-Duser.language=en', '-Duser.country=US'
}

内容的提问来源于stack exchange,提问作者Yang Shuogeng

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 14:45:05