Odd timezone behavior when running JUnit tests

I've got a wierd problem that I am at a loss to explain. Perhaps some of you IDEA experts can explain what's going on.

I've got a bunch of time utility classes with JUnit tests defined for each class. I have a JUnit run configuration that uses the "All in package" mechanism to run all my unit tests. When I run that configuration, I get a unit test failing because of code that uses the default timezone (i.e. no Locale arg passed to SimpleDateFormat) when the test expects central time zone. No problem, I can fix that code.

Here's the wierd part: When I select the individual test class that fails and run it "standalone" using a single class JUnit run configuration, the test passes. I added a couple of logging statements, and sure enough I'm getting a different default timezone depending on how I run.

To test this, I have the following code:

When I run in the "All in package" mode, the console gets the following:

When I run in the single test class mode, the console instead shows:

Can anyone explain why I see a different default timezone here?

Comment actions Permalink

I can't speak to the JUnit behaviour but it's well known that the Sun
Calendar/TimeZone/Date classes are complete crap (sorry, just venting).

Specifically in your case, TimeZone.setDefault() uses an
InheritableThreadLocal, which means that you're not actually setting the
default for the VM, as you might assume, but only for the current Thread
and any Threads started by the current Thread. I assume either you or
JUnit is using this functionality and the Thread structure differs when
running all the tests and when running the single test.

The only reliable way to set the default TimeZone for the VM is to start
your VM with -Duser.timezone=GMT or whatever.

Hope that helps,

Comment actions Permalink

Interesting... I will have to look into it. In this case, I am not setting the timezone (at least not that I'm aware of - It's someone else's code). Perhaps JUnit is at some level...

My understanding of the Java classes related to timezone is that unless you specify a time zone, them the default is used. That default, unless set using one of the mechanisms you've noted, comes from the underlying OS's timezone setting. That setting is clearly not changing here.

So, for your theory to be true, some code somewhere in the project (either JUnit, my own application's code, or IDEA's JUnit runner code) would have to be calling the setDefaultTimezone() method. Is that correct? I suppose I can search through the JUnit source code to find out if they do. Can someone from JetBrains please verify that they do nothing wierd with timezone when executing JUnit tests?


- Tim


Please sign in to leave a comment.