Tuesday, 7 December 2010

Testing cron expressions in Grails Jobs

One big problem I have is I can never remember what the cron expression is supposed to be and once I've got it in the code if it is actually correct.

Very simple test below. I create a CronTrigger and pass in the expression from the job. I then check that it will fire by passing in a Calendar object. The only key here is you can't test something in the past hence why I am adding another day to the LocalDate object.

void testJobSchedule() {
def trigger = new CronTrigger("name", "group", JobName.cronExpression)
assertTrue "job should fire at 1:15", trigger.willFireOn(time(1, 15))
}

private Calendar time(int hour, int minute) {
new LocalDate().plusDays(1).toDateTime(new LocalTime(hour, minute, 0, 0)).toCalendar(Locale.UK)
}

Hopefully this helps someone out.


No comments: