3

I have time dependent unit tests in which I have to simulate "now". I use JodaTime and when I need to simulate the value of now for purposes of time dependent testing I use DateTimeUtils.setCurrentMillisFixed(...), as suggested in the accepted answer in question Time dependent unit tests.

However, this has now caused problems when unit tests are run in parallel. Proper solution would be to make all classes obtain current time from a Clock dependency which could be mocked out in tests (as suggested in most upvoted answer in Time dependent unit tests). However, I will not have enough development resources to make that refactoring effort at the moment.

My question is is there a way to work around this by somehow specifying which tests may be run in parallel and which may not? Is there a way to work around this by using DateTimeUtils.setCurrentMillisProvider() ?

Testing framework is JUnit4, tests are run from maven.

Community
  • 1
  • 1
Krešimir Nesek
  • 5,302
  • 4
  • 29
  • 56
  • "However, I will not have enough development resources to make that refactoring effort at the moment": you could split your test cases so the refactored ones are run in parallel and the legacy tests are not, then move the cases over one by one as you refactor them. Then you would be incrementally improving things. – Raedwald Sep 03 '13 at 12:14
  • I agree, however how do I split them? How to make some tests run in parallel and some not when using JUnit and maven? – Krešimir Nesek Sep 03 '13 at 12:20

3 Answers3

2

Implement and set a CurrentMillisProvider that stores "now" in a ThreadLocal<Long>, as suggested in these Parallelism Tips:

P.S. Joda Time has DateTimeUtils which lets you change the current time used by the library. It's a global variable, but if you call DateTimeUtils.setCurrentMillisProvider with a ThreadLocal backed implementation, it'll be reasonably isolated when testing legacy code that uses Joda Time.

Joe
  • 29,416
  • 12
  • 68
  • 88
0

If the tests are started from one thread you can use a InheritableThreadLocal to store the current time.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Already mentioned by Joe implementation of DateTimeUtils backed with ThreadLocal would do the job.

Sadly, nobody has provided such implementation.
You can find one in https://github.com/restx/restx project: HERE

And later in your tests you can manipulate the time with:

ThreadLocalMillisProvider.setCurrentMillisFixed(now.getMillis)
ThreadLocalMillisProvider.setCurrentMillisSystem()

With classes which use JodaTime under the hood.

Enjoy!

Atais
  • 10,857
  • 6
  • 71
  • 111