Java 如何模拟Junit的内部方法调用
我有以下资料:Java 如何模拟Junit的内部方法调用,java,mockito,powermock,Java,Mockito,Powermock,我有以下资料: public class A{ private SOAPMessage msg; SOAPMessage getmSOAP() { return msg; } public Map<String,String> getAllProfiles(String type) throws SOAPException { NodeList profilesTypes = getmsoapRespons
public class A{
private SOAPMessage msg;
SOAPMessage getmSOAP()
{
return msg;
}
public Map<String,String> getAllProfiles(String type) throws SOAPException
{
NodeList profilesTypes = getmsoapResponse().getSOAPBody().getElementsByTagName("profileType");
...
}
}
运行B:
m_mock = spy(new A())
doReturn(m_SOAPRespones).when(m_mock ).getmsoapResponse();
两者都不起作用,我做错了什么
运行B在最后工作,有一个小错误
建议的答案也很有效 您只遗漏了一件事:您还需要在此处模拟
.getSoapBody()
的结果
对以下类别进行假设;只需替换为适当的类;还要注意,我尊重Java命名约定,您也应该:
final A mock = spy(new A());
final SOAPResponse response = mock(SOAPResponse.class);
final SOAPBody body = mock(SOAPBody.class);
// Order does not really matter, of course, but bottom up makes it clearer
// SOAPBody
when(body.whatever()).thenReturn(whatIsNeeded);
// SOAPResponse
when(response.getSoapBody()).thenReturn(body);
// Your A class
when(mock.getSoapResponse()).thenReturn(response);
when(mock.getAllProfiles("")).thenCallRealMethod();
简而言之:您需要模拟链中的所有元素。请务必遵循Java命名约定,这使以后阅读您的代码的人更容易;) 你的第二种方法看起来不错。当你说它“不起作用”时,你的确切意思是什么?你哪里对:)有一个bug:P
final A mock = spy(new A());
final SOAPResponse response = mock(SOAPResponse.class);
final SOAPBody body = mock(SOAPBody.class);
// Order does not really matter, of course, but bottom up makes it clearer
// SOAPBody
when(body.whatever()).thenReturn(whatIsNeeded);
// SOAPResponse
when(response.getSoapBody()).thenReturn(body);
// Your A class
when(mock.getSoapResponse()).thenReturn(response);
when(mock.getAllProfiles("")).thenCallRealMethod();