我有以下内容:
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");
...
}
}
我想在 getAllProfiles(String value)
中模拟对 getmsoapResponse()
的调用,并注入(inject)我自己的 SOAPMessage
。
尝试了一些不起作用的事情: 运行A:
m_mock = Mockito.mock(A.class);
Mockito.when(m_mock .getmsoapResponse()).thenReturn(m_SOAPRespones);
Mockito.when(m_mock .getAllProfiles("")).thenCallRealMethod();
运行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 命名约定,这会让以后阅读您的代码的人更容易;)
关于java - 如何模拟对 Junit 内部方法的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27757879/