来自本地 XML 的模拟 SoapClient 响应 [英] mock SoapClient response from local XML

查看:77
本文介绍了来自本地 XML 的模拟 SoapClient 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用来自文件的 XML 来模拟 \SoapClient 的响应.

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

如何在 SoapClient 从文件中返回时创建 stdClass 对象.

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

客户端已经封装了 SoapClient,因此可以轻松模拟响应.

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

我的模拟是这样的:

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

但这会返回 SimpleXml 而不是 stdClass.

But this returns SimpleXml and not stdClass.

更新:
提议的 json_encode/json_decode hack 似乎没有处理 SoapClient 返回的属性:

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

SoapClient:

SoapClient:

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

黑客:

  object(stdClass)#27 (3) {
  ["@attributes"]=>
  object(stdClass)#30 (2) {
    ["Lang"]=>
    string(2) "de"
    ["Success"]=>
    string(4) "true"

推荐答案

您可以将 SimpleXml json 编码/解码如下:

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')
                    )
                ))
            )
        );

但我建议将罐头响应明确定义为 php 类.

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

这篇关于来自本地 XML 的模拟 SoapClient 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆