Issue
I am trying to use PowerMockito
in order to test a static method in my service. I have the following test method:
@PrepareForTest(LoggingUtils.class)
@RunWith(PowerMockRunner.class)
public class SiteServiceImplTest {
@Test
public void test() {
// code omitted
PowerMockito.mockStatic(LoggingUtils.class);
Page<SiteDTO> result = siteService.findAll(request, sort);
PowerMockito.verifyStatic(LoggingUtils.class, Mockito.times(1));
}
}
But when I run this test, it throws the following error:
org.mockito.exceptions.misusing.NotAMockException: Argument passed to verify() is of type Class and is not a mock! Make sure you place the parenthesis correctly! See the examples of correct verifications:
verify(mock).someMethod();
verify(mock, times(10)).someMethod();
verify(mock, atLeastOnce()).someMethod();
So, how can I use PowerMockito
and test my static method?
The static method is as following:
LoggingUtils.info("The ...);
Solution
Verification of a static method is done in two steps:
- First call
PowerMockito.verifyStatic(Static.class)
to start verifying behavior and then - Call the static method of the
Static.class
to verify.
For example:
PowerMockito.verifyStatic(Static.class); // 1
Static.firstStaticMethod(param); // 2
See documentation
Your test should look:
@RunWith(PowerMockRunner.class)
@PrepareForTest(LoggingUtils.class)
public class ServiceTest {
@Test
public void test() {
// mock all the static methods in a class called "LoggingUtils"
PowerMockito.mockStatic(LoggingUtils.class);
// execute your test
ServiceSite siteService = new ServiceSite();
siteService.find();
// Different from Mockito, always use PowerMockito.verifyStatic(Class) first
// to start verifying behavior
PowerMockito.verifyStatic(LoggingUtils.class, Mockito.times(1));
// IMPORTANT: Call the static method you want to verify
LoggingUtils.info(anyString());
}
}
public class ServiceSite {
SiteDTO find() {
LoggingUtils.info("123");
return new SiteDTO();
}
}
Answered By - Eugene
Answer Checked By - Robin (JavaFixing Admin)