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?
As far as I see it you have three sensible options:
Inject the Calendar
instance in whatever method/class you set that day in.
private void method(final Calendar cal)
{
Date today = cal.getTime();
}
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();
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()