Fork me on GitHub

31 Mar 2009

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 Time's DateTimeUtils class to mock the current time. This enables you to have new DateTime objects, for example, use a predictable timestamp. Unfortunately it doesn't 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 don't have to add code to your domain class to enable tests to work, but on the other hand it's 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!

5 comments:

laustan said...

Date and time estimation is shockingly mind boggling. When, timekeeping was an exceptionally nearby issue, utilizing shadow tickers and sundials, so a specific perusing of the time was legitimate just at a particular area. In any case, as progress extended, and correspondences and travel turned out to be quicker and more ordinary, principles must be built up.

regards,
website

Unknown said...

Interesting post.
Get help with any type of assignments from real experts from Speedypaper.

datxoichecom said...

iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet
iphongthuynet

viju ln said...

thanks
Bergan 5 lb Travel Feeder with Handle Review

fise said...

click for info look at this site you could look here linked here site web Visit Website