如何在 Java 8 上的 maven Surefire 中设置单元测试的时区?
在 Java 7 中,这曾经与 systemPropertyVariables
一起工作,就像在以下配置中一样,但在 Java 8 中,测试只使用系统时区。
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<systemPropertyVariables>
<user.timezone>UTC</user.timezone>
</systemPropertyVariables>
为什么会这样,我该如何解决?
最佳答案
简答
Java 现在更早地读取 user.timezone
,然后再确定 systemPropertyVariables
中的属性。解决方法是提前设置,使用 argLine
:
<plugin>
...
<configuration>
<argLine>-Duser.timezone=UTC</argLine>
长答案
Java 初始化默认时区,将 user.timezone
考虑到它需要它的 first 时间,然后将其缓存在 java.util.TimeZone
。现在在读取 jar 文件时已经发生了这种情况:ZipFile.getZipEntry
现在调用 ZipUtils.dosToJavaTime
,它创建了一个初始化默认时区的 Date
实例。这不是一个万无一失的特定问题。有人称之为 bug在JDK7中。该程序用于打印 UTC 时间,但现在使用系统时区:
import java.util.*;
class TimeZoneTest {
public static void main(String[] args) {
System.setProperty("user.timezone", "UTC");
System.out.println(new Date());
}
}
一般来说,解决方法是在命令行指定时区,比如java -Duser.timezone=UTC TimeZoneTest
,或者用TimeZone.setDefault(TimeZone.getTimeZone编程设置("UTC"));
.
完整的example :
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
... could specify version, other settings if desired ...
<configuration>
<argLine>-Duser.timezone=UTC</argLine>
</configuration>
</plugin>
</plugins>
</build>
关于java - 在 Java 8 上为 Maven 单元测试设置时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23466218/