Java 使用 PowerMockito 模拟私有方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28121177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mock private method using PowerMockito
提问by Pankaj
I'm using PowerMockito to mock the private method call (privateApi) but it still makes the privateApi call which in turn makes another thirdPartCall. I'm getting into problem when thirdPartyCall throws exception. As far as I understand, if I'm mocking the privateApi, it shouldn't get into method implementation detail and return the mock response.
我正在使用 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
}
}
Here is the test case:
这是测试用例:
@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();
}
}
Console trace:
控制台跟踪:
In privateAPI
In thirdPartyCall
In publicApi
result : 20
回答by clD
You just need to change the mock method call to use doReturn
.
您只需要将模拟方法调用更改为 use doReturn
。
Example Partial Mocking of Private Method
Test code
测试代码
@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();
}
}
Console trace
控制台跟踪
In publicApi
result : 20