在Java 8中为Maven单元测试设置时区

42

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

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


使用完整的 Etc/UTC 而不是仅仅使用 UTC,因为三个字母的时区缩写已被视为过时,可能会引起混淆 - Leponzo
1个回答

81

简短回答

Java现在会在surefire设置systemPropertyVariables属性之前读取user.timezone。 解决方案是使用argLine提前设置它:

<plugin>
  ...
  <configuration>
    <argLine>-Duser.timezone=UTC</argLine>

长篇回答

Java在需要时会初始化默认时区,考虑到user.timezone,并将其缓存于java.util.TimeZone。当读取jar文件时,现在已经发生了这种情况:ZipFile.getZipEntry现在调用ZipUtils.dosToJavaTime,它创建一个Date实例,该实例初始化了默认时区。这不是surefire特定的问题。一些人将其称为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"));进行编程设置。

完整的示例请参考此处

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

6
@fge 这是无关紧要的,“new Date()`只是一个简单的例子,以便与Java 7进行比较。新时间类使用相同的默认时区,因此它们具有完全相同的问题。 - Wouter Coekaerts
3
“mvn -Duser.timezone=UTC”也不能正常工作,这很奇怪。只有“<argLine>”能够起作用。 - Sanghyun Lee
19
@Before中设置TimeZone.setDefault(TimeZone.getTimeZone("UTC"))对我有效。argLine不确定为什么不起作用。适用于JUnit 4.10和Maven 3。 - zengr
1
对我来说这个方法可行。如果在命令行中可行但在IntelliJ中不行(并且jacoco也在运行),请参考https://dev59.com/m2ct5IYBdhLWcg3wNqsg#29975159或使用zengr评论中的@Before解决方法... - rogerdpack
5
@SanghyunLee将该系统属性应用于Maven进程。默认情况下,Surefire / Failsafe将在单独的进程中运行测试。请参阅此处的“分叉测试执行”(https://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html) - Jason Young
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接