【问题标题】:Write php tests to check HTTP response code编写 php 测试来检查 HTTP 响应代码
【发布时间】:2014-04-18 10:54:02
【问题描述】:

我正在使用 phpunit 编写单元测试。

现在我想测试一下 HTTP 响应代码是否符合预期,即。类似:

$res = $req->getPage('NonExistingPage.php', 'GET');
assertTrue($res->getHttpResponseCode(), 404);

我知道 Symfony 和 Zend 可以做到这一点。 然而,我在没有使用任何框架的情况下开发了我的整个项目。而且,据我了解,如果要使用这些框架,他必须更改他的项目以采用这些框架的默认项目结构。但我不想改变我的项目中的任何东西(甚至是它的文件夹结构)。

那么有没有办法在不改变我现有项目的情况下编写这样的测试(检查 http 响应代码)?

【问题讨论】:

标签: php unit-testing phpunit http-response-codes


【解决方案1】:
assert(strpos(get_headers('http://www.nonexistingpage.com')[0],'404') !== false) 

【讨论】:

  • 当心不存在的主机错误,则404检测不到。
【解决方案2】:

虽然您不需要框架,但测试框架仍应使用 Mock 对象,然后您应该让代码相应地处理函数。例如,您的库需要对 404 错误做一些事情。不要测试 HTML 错误代码是否为 404,而是测试您的库是否正确运行。

class YourHTTPClass
{
    private $HttpResponseCode;
    public function getPage($URL, $Method)
    {
        // Do some code to get the page, set the error etc.
    }

    public function getHttpResponseCode()
    {
        return $this->HttpResponseCode;
    }

    ...
}

PHP 单元测试:

class YourHTTPClass_Test extends \PHPUnit_Framework_TestCase
{
    public function testHTMLError404()
    {
        // Create a stub for the YourHTTPClass.
        $stub = $this->getMock('YourHTTPClass');

        // Configure the stub.
        $stub->expects($this->any())
             ->method('getHttpResponseCode')
             ->will($this->returnValue(404));

        // Calling $stub->getHttpResponseCode() will now return 404
        $this->assertEquals(404, $stub->getHttpResponseCode('http://Bad_Url.com', 'GET'));      
        // Actual URL does not matter as external call will not be done with the mock
    }

    public function testHTMLError505()
    {
        // Create a stub for the YourHTTPClass.
        $stub = $this->getMock('YourHTTPClass');

        // Configure the stub.
        $stub->expects($this->any())
             ->method('getHttpResponseCode')
             ->will($this->returnValue(505));

        // Calling $stub->getHttpResponseCode() will now return 505
        $this->assertEquals(505, $stub->getHttpResponseCode('http://Bad_Url.com', 
}

通过这种方式,您已经测试了您的代码可以处理各种返回码。使用模拟对象,您可以定义多个访问选项,或使用数据提供者等...生成不同的错误代码。

您将知道您的代码将能够处理任何错误,而无需转到外部 Web 服务来验证错误。

要测试获取数据的代码,您可以执行类似的操作,实际模拟 GET 函数以返回已知信息,这样您就可以测试获取结果的代码。

【讨论】:

    【解决方案3】:
    1. $this->assertEquals($expected, $actual);
    2. 需要检查$res(不是$req->getHttpResponseCode())
    3. 查看 $req->getPage(...) 方法返回的类,找到返回 http 代码的方法。

    【讨论】:

    • $this 是什么?我认为问题中没有指定框架,示例代码只是一个猜测。
    猜你喜欢
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    相关资源
    最近更新 更多