Is there a good way at Grails to make fun of the current time using Joda time?

I am writing code that calculates the date and time with the current time. During Joda, this is achieved through the constructor (Java), since it is an immutable object. I need to be able to scoff at the fact that new DateTime() returns a certain constant moment so that I can make reasonable test statements, but leave all the other DateTime methods.

This proves a nuisance. Grails mockFor(DateTime, true) won't let me scoff at a Java constructor, but there is no obvious or readable non-constructor way to get time during Joda.

The only options available seem to include low-level JVM methods, such as JMockit or the EasyMock 3 class, that cause Grails pain. Is there a simple / easy way to achieve this?

+8
time jodatime mocking grails groovy
source share
3 answers

As a result, we created a dateService using the now() method. In unit tests, we mock him with

 domainInstance.dateService = [ now: { currentTime } ] as DateService 

where currentTime is the unit test class field. This imposes a dependency on dateService (our only almost global dependency), and for src classes you need to pass it manually.

Unit tests, OTOH, look pretty clear.

+5
source share

I know that this is already accepted, but with Joda-time you can freeze and tune it to what you like. Thus, you can freeze time, increase time, return on time. If you use Joda sequentially, your objects will get "now" like any time you set for this.

 // Stop time (and set a particular point in time): DateTimeUtils.setCurrentMillisFixed(whenever); // Advance time by the offset: DateTimeUtils.setCurrentMillisOffset(offsetFromCurrent); // Restore time (you could do this in an @After method) DateTimeUtils.setCurrentMillisSystem(); 
+18
source share

you could just use the good old-fashioned principles of OO, for example.

  interface TimeService { DateTime getCurrentTime() // other time-related methods } class JodaTimeService implements TimeService { DateTime getCurrentTime() { new DateTime() } } class MockTimeService implements TimeService { DateTime getCurrentTime() { // return a fixed point in time } } 

Your code should get a reference to the implementation of TimeService through dependency injection. In resources.groovy use MockTimeService only when running tests

 import grails.util.Environment beans = { if (Environment.current == Environment.TEST) { timeService(MockTimeService) } else { timeService(JodaTimeService) } } 
+2
source share

All Articles