在Java 8上为maven单元测试设置时区 [英] Setting timezone for maven unit tests on Java 8

查看:103
本文介绍了在Java 8上为maven单元测试设置时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java 8上的maven surefire中设置单元测试的时区?

How do I set the timezone for unit tests in maven surefire on Java 8?

使用Java 7,这曾经用于 systemPropertyVariables 就像在以下配置中一样,但是对于Java 8,测试只使用系统时区。

With Java 7 this used to work with systemPropertyVariables like in the following configuration, but with Java 8 the tests just use the system timezone.

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

推荐答案

简短回答



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

Short answer

Java now reads user.timezone earlier, before surefire sets the properties in systemPropertyVariables. The solution is to set it earlier, using argLine:

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



长答案



Java初始化默认值时区,将 user.timezone 考虑到它需要的第一个时间,然后将其缓存在 java.util.TimeZone中。现在在读取jar文件时已经发生了这种情况: ZipFile.getZipEntry 现在调用 ZipUtils.dosToJavaTime 创建一个日期初始化默认时区的实例。这不是一个特定的问题。此程序用于以UTC格式打印时间,但现在使用系统时区:

Long answer

Java initializes the default timezone, taking user.timezone into account the first time it needs it and then caches it in java.util.TimeZone. That now happens already when reading a jar file: ZipFile.getZipEntry now calls ZipUtils.dosToJavaTime which creates a Date instance that initializes the default timezone. This is not a surefire-specific problem. This program used to print the time in UTC, but now uses the system timezone:

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

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 8上为maven单元测试设置时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆