Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 667
Randomize Avatar asked Feb 14 '12 11:02

Randomize


People also ask

What is Calendar getInstance () in Java?

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.

What does calendar getInstance () getTime () this return?

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).)

How do I convert a date to a calendar in Java?

Calendar date = Calendar. getInstance(); date. set( Calendar. DAY_OF_WEEK, Calendar.


2 Answers

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); 
like image 114
GoGoris Avatar answered Sep 17 '22 15:09

GoGoris


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()

like image 24
BeRecursive Avatar answered Sep 17 '22 15:09

BeRecursive