unit testing and time travel

Sometimes the solution for a thorny problem is easy. If you are writing unit tests for a piece of code that behaves differently before and after a certain point of time you wish you could do time travel with the computer you are using to run the tests. Adjusting the system date often is inconvenient. A lot of processes depend on proper timekeeping by the operating system and often a regular user cannot adjust time for simple lack of authorization. Take my advice and stay away from the system clock.

The solution is to use Joda Time. It has a class called DateTimeUtils with a static method setCurrentMillisFixed that effectively fixes the system time for the Joda Time library to a certain value. Returning to the present is done by calling setCurrentMillisSystem after you are done time traveling

    public void before() {
        LocalDate pointInTime = new LocalDate().minusDays(10);
        DateTimeUtils.setCurrentMillisFixed(pointInTime.toDateTime(new LocalTime(0, 0, 0, 0)).getMillis());

    public void after() {