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.
I'm not too familiar with the latest Java code, but aren't you missing a finally block somewhere?
ReplyDeleteFrancois,
ReplyDeleteYeah, I guess I am. Though, it's never been a problem in practice (over the last 10 months).
Good catch.
cool idea
ReplyDelete