USer22999299
USer22999299

Reputation: 5694

How to mock a call for inner method for Junit

I have the following:

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

        ...
    }
}

I want to mock the call of getmsoapResponse() in side of getAllProfiles(String value) and to inject my own SOAPMessage.

Was trying few things which did not work: Run A:

m_mock = Mockito.mock(A.class);
Mockito.when(m_mock .getmsoapResponse()).thenReturn(m_SOAPRespones);
Mockito.when(m_mock .getAllProfiles("")).thenCallRealMethod();

Run B:

m_mock = spy(new A())
doReturn(m_SOAPRespones).when(m_mock ).getmsoapResponse();

Both did not work, what did i do wrong?


Run B did work at the end , had a small bug.

As well the suggested answer is working well.

Upvotes: 2

Views: 5286

Answers (1)

fge
fge

Reputation: 121860

You miss only one thing: you also need to mock the result of .getSoapBody() here.

Assumptions are made about classes below; just replace with the appropriate classes; note also that I respect the Java naming conventions, which you should too:

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

In short: you need to mock all elements in the chain. And please do follow Java naming conventions, it makes it easier for people who read your code later on ;)

Upvotes: 2

Related Questions