How to check response headers in laravel 4 for unit testing?

I have seen many examples of how to set headers for a response, but I cannot find a way to check the headers of a response.

For example, in a test case, I:

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 can I verify that the content type header is "application / json" or any other content type? Maybe I donโ€™t understand something?

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

Thanks!

+6
source share
4 answers

After some digging in the Symfony and Laravel docs, I was able to figure this 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')); } 
+10
source

While this is not just about testing, a good way to get a Laravel response object is to register a โ€œFinishโ€ callback. They are executed immediately after sending a response immediately before closing the application. The callback receives the request and response objects as arguments.

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

Take a look at the laravel documentation

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

Getting 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"]=> ... 
+1
source

For debugging purposes, you can simply use this:

 var_dump($response->headers); 
+1
source

Source: https://habr.com/ru/post/957532/


All Articles