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

iklwldmw  于 5个月前  发布在  Java
关注(0)|答案(1)|浏览(66)

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

字符串
为什么会这样,我该怎么解决?

2exbekwf

2exbekwf1#

简短回答

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示例,该示例将返回默认时区。特定的问题。有些人在JDK 7中称之为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"));以编程方式设置时区。
完整的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>

相关问题