3

Here is comment about setting default timezone for test code in @Before method of JUnit test. But TimeZone.setDefault is static method. Can it affect other test which are run after test with @Before and TimeZone.setDefault completes successful?

Cherry
  • 31,309
  • 66
  • 224
  • 364
  • 1
    ...you should be using the `java.time.*` classes, which includes a [`Clock`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html) class that returns a (replacement type) timezone. Is switching to them an option? It would make testing much easier (say, using a fixed clock), and `java.util.Date` has major issues, as well. Note that if your tests are being run in parallel, setting the timezone is going to cause problems (especially if multiple tests are attempting to set it to different timezones) – Clockwork-Muse Oct 28 '18 at 18:31

2 Answers2

2

There are many things to check here, it depends on how do you run the tests.

The following factors may come into considerations:

  1. Since you've tagged "maven" in a question: Maven's surefire/failsafe plugins responsible for running the tests can run multiple tests simultaneously in 1 or many JVMs, it all depends on their configurations. So tests may start failing sporadically during the build even if they pass locally.

  2. @Before and @After are called before and after each test in the test case respectively. @After is called even if the test fails. So probably memorizing the default timezone and setting it back after the test should be ok, but not "re-setting" the state in an "@After" block may lead to incorrect definitions in subsequent tests.

The better approach IMHO is using java.time.Clock abstraction. See this question for examples

Another possible option is refactoring a code to use some "factory" for providing current date / time. Then in Unit Test you could instantiate this factory and "inject" it as a dependency into the code-under-test. A kind of hand-crafted Clock

Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

It will effect the other tests (as you assumed), as it won't be reset after running a single test. Either reset it to "normal" by an @After method, or maybe change the code to take/inject the timestamp for "now" and make the code do it's calculation from there. From my experience this will give you alot more flexibility.

Arman
  • 875
  • 2
  • 8
  • 30