如何在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>
为什么会这样,我该如何解决?
答案 0 :(得分:39)
Java现在更早地读取user.timezone
,之前surefire在systemPropertyVariables
中设置了属性。解决方案是使用argLine
:
<plugin>
...
<configuration>
<argLine>-Duser.timezone=UTC</argLine>
Java初始化默认时区,将user.timezone
考虑到它需要的第一个时间,然后将其缓存在java.util.TimeZone
中。现在,在读取jar文件时已经发生了这种情况:ZipFile.getZipEntry
现在调用ZipUtils.dosToJavaTime
,这会创建一个初始化默认时区的Date
实例。这不是一个特定的问题。有些人称它为JDK7中的bug。此程序用于以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"));
以编程方式设置时区。
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>