我正在尝试使用 php 套接字为个人项目创建一个库。为此,我开始使用 phpUnit 来学习和编写(或多或少)定性库。
当我没有在 testConnection 方法中提供 try/catch 块时,php 会给出连接超时的错误(这是正常的,因为设备未连接)。但是php应该在下面的execute方法中处理异常,而不是在testConnection方法中。我似乎无法弄清楚这一点。
这是错误:
PHPUnit_Framework_Error_Warning : stream_socket_client(): unable to connect to tcp://x.x.x.x:* (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
带有不应存在的方法和 try/catch 的测试类:
public function testConnection() {
$adu = new Adu();
$adu->setPort('AS0');
$adu->setData('?');
$command = new Command('x.x.x.x', *);
$command->setAduSent($adu);
try
{
$command->execute();
}
catch (Exception $e)
{
echo $e->getMessage();
}
}
这(执行方法)是应该处理异常的地方:
public function execute()
{
try {
$this->stream = $this->createStream($this->address, $this->port, $this->timeout);
}
catch(Exception $e) {
$this->logger->error('Exception (' . $e->getCode() . '): ' . $e->getMessage() . ' on line ' . $e->getLine(), $e);
}
$this->send($this->stream, $this->aduSent);
$this->aduReceived = $this->receive($this->stream);
}
private function createStream($address, $port, $timeout = 2)
{
$stream = stream_socket_client('tcp://' . $address . ':' . $port, $errorCode, $errorMessage, $timeout);
if(!$stream) {
throw new Exception('Failed to connect(' . $errorCode . '): ' . $errorMessage);
}
return $stream;
}
解决方案
因为 try/catch 不会捕获错误/警告,所以我不得不抑制由 stream_socket_client 触发的警告。然后检查返回值是 false 还是流对象。如果为 false,则抛出适当的异常。
$stream = @stream_socket_client('tcp://' . $address . ':' . $port, $errorCode, $errorMessage, $timeout);