java - 使用 PowerMockito 模拟私有(private)方法

标签 java junit powermock

我正在使用 PowerMockito 来模拟私有(private)方法调用 (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

最佳答案

您只需将模拟方法调用更改为使用 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

关于java - 使用 PowerMockito 模拟私有(private)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28121177/

相关文章:

java.lang.Exception : No runnable methods exception in running JUnits

java - 如何使用 JUnit、EasyMock 或 PowerMock 模拟静态最终变量

java - 模拟 hibernate session

java - 管理 session phonegap Restful API?

java - 正则表达式忽略已声明的变量初始化

unit-testing - 如何避免 JUnit 测试中的多个断言?

java - 使用 PowerMock 模拟来自多个类的静态方法

java - 为什么我在尝试编译 servlet 时会收到无效标志错误?

java - 更改 edittext 上的 textview(如果可能没有按钮)

java - 使用 mysql 在 travis 上运行测试