How do I set the timezone for unit tests in maven surefire on 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?
Short answer
Java now reads
user.timezone
earlier, before surefire sets the properties insystemPropertyVariables
. The solution is to set it earlier, usingargLine
:Long answer
Java initializes the default timezone, taking
user.timezone
into account the first time it needs it and then caches it injava.util.TimeZone
. That now happens already when reading a jar file:ZipFile.getZipEntry
now callsZipUtils.dosToJavaTime
which creates aDate
instance that initializes the default timezone. This is not a surefire-specific problem. Some call it a bug in JDK7. This program used to print the time in UTC, but now uses the system timezone:In general, the solution is to specify the timezone on the command line, like
java -Duser.timezone=UTC TimeZoneTest
, or set it programmatically withTimeZone.setDefault(TimeZone.getTimeZone("UTC"));
.Full'ish example: