0

I am trying to mock Calendar.getInstance() for unit testing purpose.

I am thus using PowerMock (powermock-core:2.0.4 & powermock-module-junit4:2.0.4) and its Mockito API (powermock-api-mockito2:2.0.4).

I am well aware that similar cases do exist, but I am facing an exception that does not seem to appear on other's case.

Indeed, when doing

mockStatic(Calendar.class);
when(Calendar.getInstance()).thenReturn(aCalendar);

on a test method within a class annotated with

@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class})

I get the following error : org.mockito.exceptions.misusing.NotAMockException: Argument should be a mock, but is: class java.lang.Class.

What did I do wrong and how to solve it ?

Thanks

EnzoMolion
  • 949
  • 8
  • 25

1 Answers1

0

There are a couple issues here.

mockStatic(Calendar.class); this should be in setUp method or something.

Then you do this.

verifyStatic(Calendar.class)
when(Calendar.getInstance()).thenReturn(aCalendar);

Another important thing is the following,

@RunWith(PowerMockRunner.class)
@PrepareForTest({DateUtils.class, Calendar.class})

Any class that has static method you would like to mock should be included in @PrepareForTest either at the class level or method level, if it is used only once.

The_Martian
  • 3,684
  • 5
  • 33
  • 61