Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"headers already sent" Error returned during PHPUnit tests

I'm testing a suite of REST web services with PHPUnit. We're using output buffering in order to gzip-encode the responses. When I run a test for the service with PHPUnit, I'm getting the error:

Cannot modify header information - headers already sent by (output started at /home/dotcloud/php-env/share/php/PHPUnit/Util/Printer.php:172)

It's complaining at the point that my code echo's the output to the browser...

I was able to work around this temporarily by adding an ob_start() call at the top of the test class(es), but when I run multiple tests at once, I get this error again.

Any ideas?

like image 741
rhuff Avatar asked Jan 04 '13 06:01

rhuff


People also ask

How do I fix the headers already sent in WordPress?

If an HTML element is placed before a header call, it can cause the “Cannot Modify Header Information – Headers Already Sent By” error. To fix the error, place the HTML block after the header statement.

What causes the headers already sent error when using the?

This error may have been caused by the blank spaces before the start of the file or after the end of the file.

What is headers already sent error why we encounter this and how it can be resolved?

The first thing you need to do when you run into the “Cannot modify header information – headers already sent by” error is to open the file that's causing the problem. Then, locate the line the message indicates. In this scenario, you can reach the source of the problem using the WordPress theme editor.


1 Answers

There are several options with different advantages and disadvantages:

  1. run the tests in separate processes with @runInSeparateProcess, as you already found out. Good: better test isolation, Bad: worse performance, does not work well with global constants
  2. use --stderr flag to direct PHPUnit output to STDERR. Good: tests work as expected without changes, Bad: feels like a dirty workaround, possibly problems with CI tools
  3. don't actually send headers. Either replace the classes that use header() with stubs or if this is not easily possible or you want to do a full functional test, mock the header() function itself. More info on mocking built-in functions in this answer. Good: you can test the contents of the headers as well, your tests do rely less on global state Bad: You'll need to write more test code

I'd go for (3) and probably refactor the code as well to have a single class that's responsible for the headers and can be easily mocked.

like image 149
Fabian Schmengler Avatar answered Oct 17 '22 17:10

Fabian Schmengler