Search code examples
phpweb-servicessoapwsdlphpunit

Phpunit, mocking SoapClient is problematic (mock magic methods)


Im trying to mock SoapClient with the following code:

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

This will not work since Phpunit mockbuilder does not find the function getAuthenticateServiceSettings. This is a Soap function specified in the WSDL.

However, if i extend the SoapClient class and the getAuthenticateServiceSettings method it does work.

The problem is i have 100s of SOAP calls, all with their own parameters etc. so i dont want to mock every single SOAP function and more or less recreate the whole WSDL file...

Is there a way to mock "magic" methods?


Solution

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

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

    See example here:

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