Phpunit, mocking SoapClient is problematic (mock magic methods)

I am trying to make fun of SoapClient with the following code:

$soapClientMock = $this->getMockBuilder('SoapClient') ->disableOriginalConstructor() ->getMock(); $soapClientMock->method('getAuthenticateServiceSettings') ->willReturn(true); 

This will not work because Phpunit mockbuilder does not find the getAuthenticateServiceSettings function. This is the soap function specified in the WSDL.

However, if I extend the SoapClient class and the getAuthenticateServiceSettings method, it really works.

The problem is that I have 100 SOAP calls, all with their own parameters, etc., so I don’t want to scoff at every SOAP function and more or less recreate the entire WSDL file ...

Is there a way to mock magic methods?

+7
soap wsdl php web-services phpunit
source share
3 answers

PHPUnit allows you to stub a web service based on a wsdl file.

 $soapClientMock = $this->getMockFromWsdl('soapApiDescription.wsdl'); $soapClientMock ->method('getAuthenticateServiceSettings') ->willReturn(true); 

See an example here:

https://phpunit.de/manual/current/en/test-doubles.html#test-doubles.stubbing-and-mocking-web-services.examples.GoogleTest.php

+14
source share

I usually don't work with the \ SoapClient class directly, instead I use the Client class that uses SoapClient. For example:

 class Client { /** * @var SoapClient */ protected $soapClient; public function __construct(SoapClient $soapClient) { $this->soapClient = $soapClient; } public function getAuthenticateServiceSettings() { return $this->soapClient->getAuthenticateServiceSettings(); } } 

This way is easier to make fun of the Client class than to mock SoapClient.

+5
source share

I could not use getMockFromWsdl for the test script, so I mocked the __call method, which is called in the background:

  $soapClient = $this->getMockBuilder(SoapClient::class) ->disableOriginalConstructor() ->getMock(); $soapClient->expects($this->any()) ->method('__call') ->willReturnCallback(function ($methodName) { if ('methodFoo' === $methodName) { return 'Foo'; } if ('methodBar' === $methodName) { return 'Bar'; } return null; }); 

PS I tried to use __soapCall at first, since __call deprecated, but it did not work.

+1
source share

All Articles