Testing PHP SoapClient

When working with PHP’s soap client, it can be useful to see the actual XML that is being sent to and received from the remote web service. By default, the SoapClient class doesn’t expose the XML, but it is possible to extend the class and override a method to intercept the request and return the raw XML.

In the first code snippet, we define a new class called PlaceholderSoapClient that extends the built-in \SoapClient class. The __construct method simply calls the parent constructor with the same arguments. The important method to note is __doRequest, which is called by the soap client to actually make the SOAP request. We override this method and return the first argument, which is the raw XML request. This way, when the soap client makes a request, it will instead return the XML instead of actually making the request.


class PlaceholderSoapClient extends \SoapClient
{
    function __construct($wsdl, $options) 
    {
        parent::__construct($wsdl, $options);
    }

    function __doRequest($request, $location, $action, $version, $oneWay = 0)
    {
        return $request;
    }
}


In the second code snippet, we create an instance of our PlaceholderSoapClient class, passing in the WSDL file and a trace option. The trace option tells the soap client to keep track of the last request and response for debugging purposes. We then make a request to the web service using the MyRequestToWebService method, passing in any necessary parameters.

Finally, we use the __getLastRequest method to get the raw XML of the last soap request, which we can then assert against to make sure it contains the expected values.

Overall, this technique can be useful for debugging and testing soap clients, especially when dealing with complex requests or responses. By intercepting the raw XML, we can easily inspect and manipulate the request and response data.


$soapClientMock = new PlaceholderSoapClient('tests/services-wsdl.xml', [
   'trace' => 1,
]);

$soapClientMock->MyRequestToWebService($params);

$xmlResponseString = $soapClientMock->__getLastRequest();

$this->assertStringContainsString("<ns1:CustomerCode>abc-123</ns1:CustomerCode>", $xmlResponseString);