Search code examples
javadatejunitcalendarmocking

java: how to mock Calendar.getInstance()?


In my code I have something like this:

private void doSomething() {
   Calendar today = Calendar.getInstance();
   ....
}

How can I "mock" it in my junit test to return a specific date?


Solution

  • As far as I see it you have three sensible options:

    1. Inject the Calendar instance in whatever method/class you set that day in.

      private void method(final Calendar cal) { Date today = cal.getTime(); }

    2. Use JodaTime instead of Calendar. This is less an option and more a case of a suggestion as JodaTime will make your life a lot easier. You will still need to inject this time in to the method.

      DateTime dt = new DateTime();

      Date jdkDate = dt.toDate();

    3. Wrap Calendar inside some interface that allows you to fetch the time. You then just mock that interface and get it to return a constant Date.

      Date today = calendarInterfaceInstance.getCurrentDate()