If you have ever tried to cover phpunit with some method that call header() function, then you’ve probably faced notice like “Headers already sent”.

That happens because phpunit fetches result for each test after it was completed to give you interactivity of testing progress. To prevent such flow you have to define custom phpunit printer class that would fetch tests summary only after they all will be completed. Here is an example:

class QuietPHPUnit_ResultPrinter extends PHPUnit_TextUI_ResultPrinter
{
  protected $outputBuffer = "";

  public function __construct($out = NULL, $verbose = FALSE, $colors = FALSE, $debug = FALSE)
  {
    parent::__construct($out, $verbose, $colors, $debug);
  }

  public function write($buffer)
  {
    if ($this->out) {
      fwrite($this->out, $buffer);

      if ($this->autoFlush) {
        $this->incrementalFlush();
      }
    } else {
      if (PHP_SAPI != 'cli') {
        $buffer = htmlspecialchars($buffer);
      }

      $this->outputBuffer .= $buffer;

      if ($this->autoFlush) {
        $this->incrementalFlush();
      }
    }
  }

  public function printResult(PHPUnit_Framework_TestResult $result)
  {

    parent::printResult($result);
    print $this->outputBuffer;
  }
}

And tell phpunit to use your printer:

<phpunit
 ...
 printer="QuietPHPUnit_ResultPrinter"
/>

Or

phpunit --printer QuietPHPUnit_ResultPrinter ..

Note that phpunit allows you to specify printer class only from version 3.6.

Another problem is how to get headers list?

As you probably know headers_list() doesn’t work in CLI mode. Solution come from XDebug extension: xdebug_get_headers() perfectly works in CLI mode.

However a few problems we do not have solution for yet:

  1. How to get http status code?
  2. How to simulate file uploads without custom php extension?

If somebody has answer to this – please, let us know.