'How to create unit test for SOAPConnection.call and mock SOAPConnection?

Welcome to point out any mistake on my code, as this is my first time using SOAP and unit test.

I have a simple SoapService which create SOAPConnection and send the SOAPMessage

SoapService.java

public SOAPMessage sendSoapRequest(String url, String requestString) throws IOException, SOAPException {

    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection= soapConnectionFactory.createConnection();


    SOAPResponse soapResponse = soapConnection.call(getSoapMessage(requestString), url);
    soapConnection.close();

    return soapResponse;
}

and I have unit test class for sendSoapRequest

SOAPServiceTest.java

@SpringBootTest
@RunWith(SpringRunner.class)
public class SoapServiceTest {

    @Autowired
    SoapService soapService;

    @Mock
    SOAPConnection mockSoapConnection;

    private SOAPMessage mockSoapResponse = mock(SOAPMessage.class);

    @Test
    public void testSendSoapMessage() throws IOException, SOAPException{

        when(mockSoapConnection.call(any(SOAPMessage.class), anyString())).thenReturn(mockSoapResponse);

        SOAPMessage soapResponse = soapService.sendSoapRequest("http://test.com/test.asmx", "SampleSoapRequestString...");

        Assert.assertNotNull(soapResponse);
        Assert.assertEquals(soapResponse,mockSoapResponse);
    }
}

Referring the code

when(mockSoapConnection.call(any(SOAPMessage.class),anyString())).thenReturn(mockSoapResponse);

it should return mockSoapResponse but it didn't, it actually trying to send the SOAPMessage to the dummy url "http://test.com/test.asmx" when comes to this line

SOAPResponse soapResponse = soapConnection.call(getSoapMessage(requestString), url);.

So my questions are

  1. What is the correct way to have a unit test for 'sendSoapRequest`?
  2. Is this the correct way to mock the SOAPConnection and define the behavior using Mockito.when ?
  3. Am I missing any setup/configuration on the mock ?

I found a related question but it didn't show the complete setup: Java - Mocking soap call with SOAPMessage request

Appreciate for any comment/idea/guide, because I'm really out of idea to get this work. Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source