I’m writing some code that does date and time calculations against the current time. In Joda time, this is accessed through a (Java) constructor, as it is an immutable object. I need to be able to mock so that new DateTime() returns a specific constant instant so I can do sensible test assertions, but leave all other DateTime methods alone.
This is proving nasty. Grails mockFor(DateTime, true) won’t let me mock a Java constructor, yet there is no obvious or readable non-constructor way of getting the time in Joda time.
The only available options seem to involve low-level JVM techniques like JMockit or EasyMock 3 class mocking, which are a pain from Grails. Is there a simple/straightforward way to achieve this?
We ended up creating
dateServicewithnow()method. In unit tests we mock it withwhere
currentTimeis a unit test class field. This imposes everybody’s dependency ondateService(our only nearly-global dependency), and forsrcclasses one has to pass it by hand.Unit tests, OTOH, look pretty clear with it.