我正在使用 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
您只需更改模拟方法调用即可使用doReturn
.
私有方法的部分模拟示例 https://github.com/powermock/powermock/wiki/MockPrivate
测试代码
@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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)