如何为Junit模拟内部方法的调用

时间:2015-01-03 18:03:33

标签: java mockito powermock

我有以下内容:

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");

        ...
    }
}

我想模仿getmsoapResponse()旁边getAllProfiles(String value)的电话并注入我自己的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();

两者都不起作用,我做错了什么?


Run B在最后工作,有一个小bug。

建议的答案也很好。

1 个答案:

答案 0 :(得分:2)

你只想念一件事:你还需要在这里嘲笑.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命名约定,以便以后阅读代码的人们更容易;)