使用 PowerMockito 从 Java 中的其他 类 模拟静态函数

Mocking static functions from other classes in Java using PowerMockito

我已经编写了用于测试 class Main 中名为 functionMain() 的函数的测试用例。我看到有人使用 PowerMockito 来测试正在测试的 class Main 中的静态函数。

但在我的例子中,functionMain() 正在使用来自另一个名为 Branch 的 class 的静态函数,该函数名为 staticBranchFunction()

我想在 Main class 的测试中模拟 staticBranchFunction()

这个主函数实际上调用了来自不同classes Branch1Branch2等的静态函数

请帮忙。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.verifyStatic;

@RunWith(PowerMockRunner.class)
@PrepareForTest({Boom.class})
public class DocTest {

    public String boomWrapper() {
        return Boom.detonate();
    }

    @Test
    public void testBoom() {
        mockStatic(Boom.class);
        when(Boom.detonate()).thenReturn("defused");
        String actual = boomWrapper();
        verifyStatic(Boom.class, times(1));
        Boom.detonate();
        assertEquals("defused", actual);
    }    
}

class Boom {
    private static final String BOOM = "Boom!";  
    public static String detonate() {
        return BOOM;
    }
}

依赖关系:

junit:junit:4.12  
org.mockito:mockito-core:2.13.0  
org.powermock:powermock-module-junit4:2.0.0-beta.5  
org.powermock:powermock-api-mockito2:2.0.0-beta.5  

描述:

更多支持版本请阅读:Mockito + PowerMock, other supported frameworks 要求:

  • 列出 @PrepareForTest({Boom.class}) 中的所有静态 类,用逗号分隔。
  • 通过 PowerMockito.mockStatic(Boom.class) 以逗号分隔 类 模拟所有静态 类。
  • 使用常规的 mockito 方法来设置您的期望,例如 Mockito.when(Boom.detonate()).thenReturn("defused")
  • 通过PowerMockito.verifyStatic(Boom.class, Mockito.times(1)); Boom.detonate();验证行为重要提示:每个方法验证需要调用PowerMockito.verifyStatic(Boom.class)

有关 PowerMock wiki 的更多详细信息。