防止PHP在Behat中测试错误的SoapClient连接时抛出错误和异常


Preventing PHP from throwing errors and exceptions when testing for a bad SoapClient connection in Behat

我们正在设置SOAP服务器,我专门在Behat中为其创建自动化测试。我遇到的问题是,我试图测试到SOAP服务器的连接的身份验证,特别是试图编写测试,以确保在没有提供用户名和密码的情况下无法连接。

然而,每次在没有添加HTTP身份验证(并且故意禁用WSDL缓存)的情况下运行测试时,我都会收到一个PHP警告,该警告会在控制台屏幕上弹出一个错误跟踪。

这是一个PHP警告,上面写着:

PHP Warning:  SoapClient::SoapClient(http://cti.local/api/v1/companies/d1/soap?wsdl): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized

我希望能够抑制该错误,并确保在声明新客户端时返回NULL或负数。为此,我尝试在"new"关键字之前添加"@"符号,并将调用包装在不引发异常的try/catch语句中。但这行不通。我还试着在行首加上"@"符号,但没有成功。

那是使用PHP内置的SOAP客户端类。这似乎是一条很棒的路,直到我遇到这个问题。因此,在用尽我能找到的所有选项后,我尝试设置Zend SOAP客户端并使用它。结果发现它似乎扩展了PHP的内置SoapClient类。所以这也不起作用。

不幸的是,我们对API的所有调用都使用HTTP验证,包括对WSDL的调用。目前我正在本地运行API的签出副本(因为我们还没有在环境中设置它)。我知道,当我输入正确的身份验证时,它会很好地工作。但我想确保我的自动化Behat测试能够成功测试,并在我验证连接身份验证失败时返回测试通过的消息。

连接呼叫示例:

/**
 * SOAP connection initiation.
 *
 * @param string $soapURL
 * @param string $options (optional, no implemented yet)
 *
 * @Given /^I connect to a soap service at "([^"]*)"$/
 */
public function iConnectToASoapServiceAt($soapURL) {
    $this->soapURL = $soapURL;
    try {
        $this->client = @new Zend'Soap'Client($soapURL, $this->options);
        $this->soapFunctions = $this->client->getFunctions();
    }
    catch ('Exception $e) {
        #For testing when it fails we cannot actually throw an error here.
        #throw new Exception("Error connecting to SOAP server.");
    }
}
/**
 * @Given /^soap returns an error$/
 */
public function soapReturnsAnError() {
    if ($this->client !== NULL && $this->soapFunctions !== NULL) {
        throw new Exception("SOAP connection did not fail as expected.");
    }
}

有人有什么想法吗?我需要能够以自动的方式测试成功的连接和不成功的连接,不会出错并终止PHP调用。

@仅抑制单个函数调用的错误。

尝试在执行失败的身份验证代码之前更改错误报告级别,然后再将其恢复:

$level = error_reporting(E_ERROR | E_PARSE); 
// your code with failed authentication here
error_reporting($level);