LostFocus

Hi, I'm Dominik Schwind, friend of the internet. Here is /now.
Say hello to me on Twitter or maybe even subscribe to my weekly newsletter.

September 13, 2022

It is surprisingly hard to mock the stdClass response that we get from a SoapClient – there are workaround with json_encode/json_decode but that is really not a nice way to got about these things. SimpleXML doesn’t help, so why not use the SoapClient itself? Thanks to this comment on StackOverflow we know how to do these things now.

Let’s assume we have an example response and the WSDL file and that’s how we get the response: (and yes, I’m aware of the fact that I could just manually do that and have the finished stdClass in the test, but that seems tedious.)

$method = 'getData';
$mockResonseFile = 'soapResponse.xml';
$mockWsdl = 'test.wsdl';

$xml = file_get_contents($mockResonseFile);

$soapClientMock = $this->getMockBuilder(SoapClient::class)
    ->setConstructorArgs([$mockWsdl])
    ->onlyMethods(['__doRequest'])
    ->getMock();

$soapClientMock->expects($this->once())->method('__doRequest')->willReturn($xml);

$response = $soapClientMock->__soapCall($method, []);