java: how to mock Calendar.getInstance()?

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

Leave a Comment