【问题标题】:Mocking static functions from other classes in Java using PowerMockito使用 PowerMockito 模拟 Java 中其他类的静态函数
【发布时间】:2018-02-17 13:37:11
【问题描述】:

我已经编写了测试用例来测试类Main 中的一个函数,称为functionMain()。我见过有人使用 PowerMockito 来测试正在测试的 Main 类中的静态函数。

但就我而言,functionMain() 正在使用另一个名为 Branch 的类中的静态函数,名为 staticBranchFunction()。

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

这个主函数实际上调用了来自不同类Branch1、Branch2等的静态函数。

请帮忙。

【问题讨论】:

  • 这实际上回答了如何测试来自被测试的同一类的静态方法,而不是来自不同类的静态函数。
  • 你能给我们看一些代码吗?
  • 是的,一点点代码将帮助我们理解清楚
  • 您是否正在从 junit 测试/调用 functionMain(),并且它已经调用了您要模拟的其他静态方法?

标签: java unit-testing junit mockito powermock


【解决方案1】:
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.when(Boom.detonate()).thenReturn("defused")
  • 通过PowerMockito.verifyStatic(Boom.class, Mockito.times(1)); Boom.detonate(); 验证行为重要提示:您需要在每个方法验证中调用PowerMockito.verifyStatic(Boom.class)。

更多详情请关注PowerMock wiki。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    相关资源
    最近更新 更多