Tuesday, February 14, 2017
Joda Time and Grails Auto Timestamping
Joda Time and Grails Auto Timestamping
The Joda-Time Plugin docs state that Grails auto-timestamping works with Joda-Time properties which is the case. However, when testing it can be useful to take advantage of Joda Times DateTimeUtils
class to mock the current time. This enables you to have new DateTime
objects, for example, use a predictable timestamp. Unfortunately it doesnt play nicely with Grails auto-timestamping which under the covers uses System.currentTimeMillis()
. There are a couple of solutions to this. You can disable the auto-timestamping and define your own beforeInsert
event which enables you to use DateTimeUtils.setCurrentMillisFixed
. For example:
static mapping = {
autoTimestamp false
}
def beforeInsert = {
dateCreated = new DateTime()
}
The other option would be to mock out the value returned by System.currentTimeMillis()
. This has the advantage of meaning you dont have to add code to your domain class to enable tests to work, but on the other hand its all to easy to have such meta class modifications leak from test to test by not being torn down properly.
On a related note the next release of the Joda-Time plugin will bind additional methods to DateTimeUtils
to scope mocking of the current timestamp, for example:
DateTimeUtils.withCurrentMillisFixed(aLong) {
// do some stuff that requires a mocked current time
}
No more forgetting to call DateTimeUtils.setCurrentMillisSystem()
in your tearDown
method!
Available link for download