在Java 8上设置maven单元测试的时区

时间:2014-05-05 06:32:09

标签: java maven timezone java-8 surefire

如何在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>

为什么会这样,我该如何解决?

1 个答案:

答案 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>