简体   繁体   中英

How do I inspect response headers in laravel 4 for unit testing?

I have seen many examples on how to set headers on a response but I cannot find a way to inspect the headers of a response.

For example in a test case I have:

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'
}

How would I go about testing that the content-type header is 'application/json' or any other content-type? Maybe I'm misunderstanding something?

The controllers I have can do content negation with the Accept header and I want to make sure the content type in the response is correct.

Thanks!

After some digging around in the Symfony and Laravel docs I was able to figure it out...

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

While not specifically about testing, a nice way of getting at Laravel's response object is to register a 'Finish' callback. These are executed just after the response is delivered, right before the app closes. The callback receives the request and the response objects as arguments.

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

Take a look at the laravel documentation

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

Retrieving A Request Header

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

Another way would be to use getallheaders() :

var_dump(getallheaders());

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

出于调试目的,您可以使用:

var_dump($response->headers);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM