Test PHP headers with PHPUnit Test PHP headers with PHPUnit php php

Test PHP headers with PHPUnit


The issue is that PHPUnit will print a header to the screen and at that point you can't add more headers.

The work around is to run the test in an isolated process. Here is an example

<?phpclass FooTest extends PHPUnit_Framework_TestCase{    /**     * @runInSeparateProcess     */    public function testBar()    {        header('Location : http://foo.com');    }}

This will result in:

$ phpunit FooTest.phpPHPUnit 3.6.10 by Sebastian Bergmann..Time: 1 second, Memory: 9.00MbOK (1 test, 0 assertions)

The key is the @runInSeparateProcess annotation.

If you are using PHPUnit ~4.1 or something and get the error:

PHP Fatal error:  Uncaught Error: Class 'PHPUnit_Util_Configuration' not found in -:378Stack trace:#0 {main}  thrown in - on line 378Fatal error: Uncaught Error: Class 'PHPUnit_Util_Configuration' not found in - on line 378Error: Class 'PHPUnit_Util_Configuration' not found in - on line 378Call Stack:    0.0013     582512   1. {main}() -:0

Try add this to your bootstrap file to fix it:

<?phpif (!defined('PHPUNIT_COMPOSER_INSTALL')) {    define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/path/to/composer/vendors/dir/autoload.php');}


Although running the test in a separate process does fix the problem, there's a noticeable overhead when running a large suite of tests.

My fix was to direct phpunit's output to stderr, like so:

phpunit --stderr <options>

That should fix the problem, and it also means that you don't have to create a wrapper function and replace all occurrences in your code.


As an aside: For me headers_list() kept returning 0 elements. I noticed @titel's comment on the question and figured it deserves special mention here:

Just wanted to cover this if there are some other people interested in this as well. headers_list() doesn't work while running PHPunit (which uses PHP CLI) but xdebug_get_headers() works instead.

HTH