Php 单元测试:使用Guzzle 5模拟超时
我正在使用Guzzle 5.3,希望测试我的客户端是否抛出Php 单元测试:使用Guzzle 5模拟超时,php,unit-testing,exception,timeout,guzzle,Php,Unit Testing,Exception,Timeout,Guzzle,我正在使用Guzzle 5.3,希望测试我的客户端是否抛出TimeOutException 那么,如何模拟Guzzle客户端,抛出一个GuzzleHttp\Exception\ConnectException 要测试的代码 public function request($namedRoute, $data = []) { try { /** @noinspection PhpVoidFunctionResultUsedInspection */ /**
TimeOutException
那么,如何模拟Guzzle客户端,抛出一个GuzzleHttp\Exception\ConnectException
要测试的代码
public function request($namedRoute, $data = [])
{
try {
/** @noinspection PhpVoidFunctionResultUsedInspection */
/** @var \GuzzleHttp\Message\ResponseInterface $response */
$response = $this->httpClient->post($path, ['body' => $requestData]);
} catch (ConnectException $e) {
throw new \Vendor\Client\TimeOutException();
}
}
更新:
正确的问题是:如何使用Guzzle 5抛出异常?或者,如何使用Guzzle 5测试catch块?您可以借助
Guzzle http\Subscriber\Mock
对象中的addException
方法测试catch
块中的代码
这是完整的测试:
/**
* @expectedException \Vendor\Client\Exceptions\TimeOutException
*/
public function testTimeOut()
{
$mock = new \GuzzleHttp\Subscriber\Mock();
$mock->addException(
new \GuzzleHttp\Exception\ConnectException(
'Time Out',
new \GuzzleHttp\Message\Request('post', '/')
)
);
$this->httpClient
->getEmitter()
->attach($mock);
$this->client = new Client($this->config, $this->routing, $this->httpClient);
$this->client->request('any_route');
}
在单元测试中,我将GuzzleHttp\Exception\ConnectException
添加到模拟中。之后,我将mock添加到发射器,最后,我调用我想要测试的方法,request
参考:
如果您知道服务器的执行超时值,为什么不尝试引入php sleep或usleep来强制等待一个操作完成?超时设置在
httpClient
中,并创建与服务器的连接。我认为当我有一个模拟的httpClient
(Guzzle)时,创建/模拟服务器不是一个好主意。只需要知道如何用这个模拟抛出异常。好的,明白了。对不起,我帮不上什么忙了。