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
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.