Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mock SoapClient response from local XML

I would like to mock the response of a \SoapClient with XML from a file.

How can i create a stdClass object just as the SoapClient returns from a file.

The client already wraps the SoapClient, so can easily mock the response.

My mock is like this:

$soapClient->expects($this->once())
            ->method('call')
            ->will(
                $this->returnValue(
                    simplexml_load_string(
                        file_get_contents(__DIR__ . '/../../../Resources/file.xml')
                    )
                )
            );

But this returns SimpleXml and not stdClass.

Update:
The proposed json_encode / json_decode hack doesnt seem to handle attributes as the SoapClient returns them:

SoapClient:

object(stdClass)[4571]
  public 'Lang' => string 'de' (length=2)
  public 'Success' => boolean true

Hack:

  object(stdClass)#27 (3) {
  ["@attributes"]=>
  object(stdClass)#30 (2) {
    ["Lang"]=>
    string(2) "de"
    ["Success"]=>
    string(4) "true"
like image 791
ivoba Avatar asked Apr 04 '16 15:04

ivoba


1 Answers

You can json encode/decode SimpleXml as following:

$soapClient->expects($this->once())
        ->method('call')
        ->will(
            $this->returnValue(
                json_decode(json_encode(
                    simplexml_load_string(
                        file_get_contents(__DIR__ . '/../../../Resources/file.xml')
                    )
                ))
            )
        );

But I would advise to explicitly define the canned response as a php class.

like image 152
Alex Blex Avatar answered Oct 06 '22 21:10

Alex Blex