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?
The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.
Calendar. getInstance(). getTime() : Returns a Date object representing this Calendar's time value (millisecond offset from the Epoch(January 1, 1970 00:00:00.000 GMT (Gregorian).)
Calendar date = Calendar. getInstance(); date. set( Calendar. DAY_OF_WEEK, Calendar.
You can mock it using PowerMock in combination with Mockito:
On top of your class:
@RunWith(PowerMockRunner.class) @PrepareForTest({ClassThatCallsTheCalendar.class})
The key to success is that you have to put the class where you use Calendar in PrepareForTest instead of Calendar itself because it is a system class. (I personally had to search a lot before I found this)
Then the mocking itself:
mockStatic(Calendar.class); when(Calendar.getInstance()).thenReturn(calendar);
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With