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 obje
you could just use good old-fashioned OO principles, e.g.
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 an implementation of TimeService
via dependency injection. In resources.groovy
use the MockTimeService
only when running the tests
import grails.util.Environment
beans = {
if (Environment.current == Environment.TEST) {
timeService(MockTimeService)
} else {
timeService(JodaTimeService)
}
}