black and yellow analog clock

Mocking Time with Joda

A big project I have been developing over the last year has been an automated billing system. There is a part of it that involves scheduling bills, and has a lot of pieces that need to know various dates - when bills are due, when they were created, and the current time. We are trying to write good unit tests, and I am trying to make sure the parts that deal with sensitive date calculations have good tests.

Some languages and frameworks, such as Rails, make mocking the system time relatively easy. In Java, however, the time comes from a global static method - System.currentTimeMillis(). Thankfully, the fine folks that developed the Joda Time framework came up with a solution to this.

I've been using this framework for years, and I just realized these methods were available in DateTimeUtils:

  • DateTimeUtils.setCurrentMillisFixed
  • DateTimeUtils.setCurrentMillisOffset
  • DateTimeUtils.setCurrentMillisSystem

The constructor for DateTime and related classes calls DateTimeUtils.currentTimeMillis instead of System.currentTimeMillis(). The other methods on DateTimeUtils allow you to fix the clock to a specific millisecond, an offset from current time in milliseconds, or restore the clock to the actual system lock.

Here is how you could use it in a JUnit test:

public class TimeTest {
  private DateTime today;
  private DateTime yesterday;
  @Before
  public void setup() {
      today = new DateTime();
      yesterday = today.minusDays(1);
      DateTimeUtils.setCurrentMillisFixed(yesterday.getMillis());
  }
  @After
  public void tearDown() {
      DateTimeUtils.setCurrentMillisSystem();
  }
  @Test
  public void test() {
      assertTrue(new DateTime().getMillis() == yesterday.getMillis());
  }
}

Leave a Reply