Freezing Joda Time
Join the DZone community and get the full member experience.
Join For FreeOnce 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.
The Freeze class is very simple:
The Snippet class is even more simple:
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.
Test method
IT
Mark (designation)
Testing
Clock (cryptography)
Reset (computing)
Assertion (software development)
Snippet (programming)
Opinions expressed by DZone contributors are their own.
Trending
-
Merge GraphQL Schemas Using Apollo Server and Koa
-
Mastering Time Series Analysis: Techniques, Models, and Strategies
-
Exploratory Testing Tutorial: A Comprehensive Guide With Examples and Best Practices
-
Microservices With Apache Camel and Quarkus
Comments