Tuesday, June 23, 2009

Freezing Joda Time

Once upon a time Mark Needham wrote about freezing Joda Time. Mark gives all the important details for freezing time (which is often helpful for testing), but I came up with some additional code that I like to add on top of his example.

Two things bother me about Mark's example. First of all, I always like the last line of my test to be the assertion. It's not a law, but it is a guideline I like to follow. Secondly, I don't like having to remember that I need to reset the time back to following the system clock.

I came up with the following idea. It's definitely a poor man's closure, but it does the job for me.
    
@Test
public void shouldFreezeTime() {
Freeze.timeAt("2008-09-04").thawAfter(new Snippet() {{
assertEquals(new DateTime(2008, 9, 4, 1, 0, 0, 0), new DateTime());
}});
}

The Freeze class is very simple:

public class Freeze {

public static Freeze timeAt(String dateTimeString) {
DateTimeUtils.setCurrentMillisFixed(JodaDateTime.create(dateTimeString).getMillis());
return new Freeze();
}

public void thawAfter(Snippet snippet) {
DateTimeUtils.setCurrentMillisSystem();
}
}

The Snippet class is even more simple:

public class Snippet {}

Using this code I can keep my assertions as close to the end of the test method as possible, and it's not possible to forget to reset the time back to the system clock.

3 comments:

  1. I'm not too familiar with the latest Java code, but aren't you missing a finally block somewhere?

    ReplyDelete
  2. Anonymous9:25 AM

    Francois,
    Yeah, I guess I am. Though, it's never been a problem in practice (over the last 10 months).

    Good catch.

    ReplyDelete

Note: Only a member of this blog may post a comment.