【问题标题】:Exception not handled in correct method using PhpUnit使用 PhpUnit 以正确的方法处理异常
【发布时间】:2014-05-18 18:38:53
【问题描述】:

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

【问题讨论】:

    标签: php exception phpunit try-catch php-socket


    【解决方案1】:

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

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

    【讨论】:

    • Tnx 获取信息!但我怎样才能避免警告?因为要记住,无法建立连接。除非我不使用 stream_socket_client 并从头开始编写套接字。并检查是否有超时,然后自己抛出异常,如果可能的话。
    猜你喜欢
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    相关资源
    最近更新 更多