If you can't use xdebug_get_headers on your system, another approach is to mock the header function.
I'm using the following now, which works great. Lets say you have this code...
<?php
header('Content-type: text/plain; charset=UTF-8');
...
I replace header
with a header function which is testable like this...
<?php
Testable::header('Content-type: text/plain; charset=UTF-8');
...
The Testable class is implemented as follows. Note that functions just need to be prepended with Testable::
. Otherwise they work just the same as the usual functions.
class Testable {
private static $headers=array();
static function header($header) {
if (defined('UNIT_TESTING')) {
self::$headers[]=$header;
} else {
header($header);
}
}
public static function reset() {
self::$headers=array();
}
public static function headers_list() {
if (defined('UNIT_TESTING')) {
return self::$headers;
} else {
return headers_list();
}
}
}
Now all you need to do is define UNIT_TESTING
in your tests, but not in production. Then when you come to test your headers, just call Testable::headers_list()
.
You should of course add methods for setcookie, headers_sent and any other functions which issue HTTP headers.