在 Java 8 上为 Maven 单元测试设置时区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23466218/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting timezone for maven unit tests on Java 8
提问by Wouter Coekaerts
How do I set the timezone for unit tests in maven surefire on Java 8?
如何在 Java 8 上的 maven surefire 中设置单元测试的时区?
With Java 7 this used to work with systemPropertyVariableslike in the following configuration, but with Java 8 the tests just use the system timezone.
在 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>
Why is that, and how do I fix it?
为什么会这样,我该如何解决?
采纳答案by Wouter Coekaerts
Short answer
简答
Java now reads user.timezoneearlier, before surefire sets the properties in systemPropertyVariables. The solution is to set it earlier, using argLine:
Java 现在读取user.timezone更早,之前surefire 将属性设置为systemPropertyVariables. 解决方案是提前设置,使用argLine:
<plugin>
...
<configuration>
<argLine>-Duser.timezone=UTC</argLine>
Long answer
长答案
Java initializes the default timezone, taking user.timezoneinto account the firsttime it needs it and then caches it in java.util.TimeZone. That now happens already when reading a jar file: ZipFile.getZipEntrynow calls ZipUtils.dosToJavaTimewhich creates a Dateinstance that initializes the default timezone. This is not a surefire-specific problem. Some call it a bugin JDK7. This program used to print the time in UTC, but now uses the system timezone:
Java 初始化默认时区,考虑user.timezone到它第一次需要它,然后将它缓存在java.util.TimeZone. 现在在读取 jar 文件时已经发生了:ZipFile.getZipEntry现在调用ZipUtils.dosToJavaTime它创建一个Date初始化默认时区的实例。这不是一个万无一失的特定问题。有人称之为JDK7 中的错误。该程序过去用于打印 UTC 时间,但现在使用系统时区:
import java.util.*;
class TimeZoneTest {
public static void main(String[] args) {
System.setProperty("user.timezone", "UTC");
System.out.println(new Date());
}
}
In general, the solution is to specify the timezone on the command line, like java -Duser.timezone=UTC TimeZoneTest, or set it programmatically with TimeZone.setDefault(TimeZone.getTimeZone("UTC"));.
通常,解决方案是在命令行上指定时区,例如java -Duser.timezone=UTC TimeZoneTest,或者使用TimeZone.setDefault(TimeZone.getTimeZone("UTC"));.
Full'ish 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>

