【问题标题】:How do I inspect response headers in laravel 4 for unit testing?如何检查 laravel 4 中的响应标头以进行单元测试?
【发布时间】:2014-12-18 09:45:04
【问题描述】:

我看过很多关于如何在响应中设置标头的示例,但我找不到检查响应标头的方法。

例如在一个测试用例中我有:

public function testGetJson()
{
    $response = $this->action('GET', 'LocationTypeController@index', null, array('Accept' => 'application/json'));
    $this->assertResponseStatus(200);
    //some code here to test that the response content-type is 'application/json'
}

public function testGetXml()
{
    $response = $this->action('GET', 'LocationTypeController@index', null, array('Accept' => 'text/xml'));
    $this->assertResponseStatus(200);
    //some code here to test that the response content-type is 'text/xml'
}

我将如何测试内容类型标头是“应用程序/json”或任何其他内容类型?也许我误解了什么?

我拥有的控制器可以使用 Accept 标头进行内容否定,我想确保响应中的内容类型正确。

谢谢!

【问题讨论】:

  • 试试Request::header('accept');Response::header('accept');

标签: php laravel


【解决方案1】:

在 Symfony 和 Laravel 文档中进行了一些挖掘之后,我能够弄清楚...

public function testGetJson()
{
    // Symfony interally prefixes headers with "HTTP", so 
    // just Accept would not work.  I also had the method signature wrong...
    $response = $this->action('GET', 'LocationTypeController@index',
        array(), array(), array(), array('HTTP_Accept' => 'application/json'));
    $this->assertResponseStatus(200);
    // I just needed to access the public
    // headers var (which is a Symfony ResponseHeaderBag object)
    $this->assertEquals('application/json', 
        $response->headers->get('Content-Type'));
}

【讨论】:

    【解决方案2】:

    虽然不是专门关于测试,但获取 Laravel 响应对象的一个​​好方法是注册一个“完成”回调。这些是在响应交付后、应用关闭之前执行的。回调接收请求和响应对象作为参数。

    App::finish(function($request, $response) {
        if (Str::contains($response->headers->get('content-type'), 'text/xml') {
            // Response is XML
        }    
    }
    

    【讨论】:

    • 您的Str::cotains 有错字。由于 StackOverflow 需要至少六个字符编辑,我无法对其进行编辑。
    【解决方案3】:

    看看laravel documentation

    Request::header('accept');  // or
    Response::header('accept');
    

    检索请求标头

    $value = Request::header('Content-Type');

    另一种方法是使用getallheaders()

    var_dump(getallheaders());
    
    // array(8) {
    //   ["Accept"]=>
    //   string(63) "text/html[...]"
    //   ["Accept-Charset"]=> ...
    

    【讨论】:

    • 虽然有用,但我想测试在测试中创建的实际 $response 对象
    【解决方案4】:

    出于调试目的你可以简单地使用这个:

    var_dump($response->headers);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-05
      • 2014-10-01
      • 2018-08-21
      • 2022-01-20
      • 1970-01-01
      • 2013-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多