【问题标题】:Mock private method using PowerMockito使用 PowerMockito 模拟私有方法
【发布时间】:2015-03-23 03:46:51
【问题描述】:

我正在使用 PowerMockito 来模拟私有方法调用 (privateApi),但它仍然会调用 privateApi,而调用又会调用另一个 thirdPartCall。当thirdPartyCall 抛出异常时,我遇到了问题。据我了解,如果我在模拟 privateApi,它不应该进入方法实现细节并返回模拟响应。

public class MyClient {

    public void publicApi() {
        System.out.println("In publicApi");
        int result = 0;
        try {
            result = privateApi("hello", 1);
        } catch (Exception e) {
            Assert.fail();
        }
        System.out.println("result : "+result);
        if (result == 20) {
            throw new RuntimeException("boom");
        }
    }

    private int privateApi(String whatever, int num) throws Exception {
        System.out.println("In privateAPI");
        thirdPartyCall();
        int resp = 10;
        return resp;
    }

    private void thirdPartyCall() throws Exception{
        System.out.println("In thirdPartyCall");
        //Actual WS call which may be down while running the test cases
    }
}

这是测试用例:

@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClient.class)
public class MyclientTest {

    @Test(expected = RuntimeException.class)
    public void testPublicAPI() throws Exception {
        MyClient classUnderTest = PowerMockito.spy(new MyClient());
        PowerMockito.when(classUnderTest, "privateApi", anyString(), anyInt()).thenReturn(20);
        classUnderTest.publicApi();
    }
}

控制台跟踪:

In privateAPI
In thirdPartyCall
In publicApi
result : 20

【问题讨论】:

    标签: java junit powermock


    【解决方案1】:

    您只需将模拟方法调用更改为使用doReturn。

    Example Partial Mocking of Private Method

    测试代码

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(MyClient.class)
    public class MyClientTest {
    
        @Test(expected = RuntimeException.class)
        public void testPublicAPI() throws Exception {
            MyClient classUnderTest = PowerMockito.spy(new MyClient());
    
            // Change to this  
    
            PowerMockito.doReturn(20).when(classUnderTest, "privateApi", anyString(), anyInt());
    
            classUnderTest.publicApi();
        }
    }
    

    控制台跟踪

    In publicApi
    result : 20
    

    【讨论】:

    • 您好,谢谢您的回答,请您看看我与此相关的问题:stackoverflow.com/questions/35561709/…
    • 无效私有方法怎么样?
    • 您能否使用 powerMockito 提供一些带有私有方法的 void 代码? @cID
    • @anandkrish - 你能帮我解决stackoverflow.com/questions/52052648/…吗?
    • @clD - 为什么我们期望这里有 RunTimeException ?如果我们不想一概而论,那我们需要改变什么?
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 2014-09-21
    • 2014-10-24
    • 1970-01-01
    • 2018-11-29
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多