PowerMockito.verifyStatic 方法无效

PowerMockito.verifyStatic method does not work

我正在尝试使用 PowerMockito 来测试我服务中的静态方法。我有以下测试方法:

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

但是当我运行这个测试时,它抛出以下错误:

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

那么,如何使用 PowerMockito 并测试我的静态方法?

静态方法如下:

LoggingUtils.info("The ...);

静态方法的验证分两步完成:

  1. 首先调用PowerMockito.verifyStatic(Static.class)开始验证行为,然后
  2. 调用Static.class的静态方法进行验证。

例如:

PowerMockito.verifyStatic(Static.class); // 1
Static.firstStaticMethod(param); // 2

documentation

您的测试应如下所示:

@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();
    }
}