在使用PhpUnit的正确方法中未处理异常


Exception not handled in correct method using PhpUnit

我正在尝试使用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.)

Testclass与方法和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();
    }
}

这(execute方法)是应该处理异常的地方:

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

stream_socket_client语句产生一个警告,而不是一个Exception,并且警告不会被try/catch块捕获。

但是PHPUnit会捕获警告,并在这种情况下抛出一个Exception,因此会触发一个错误。您可以配置PHPUnit不将警告视为错误,尽管我不建议这样做。您的代码应该没有警告。PHPUnit)文档。