Search code examples
phpsimpletestunit-testing

Problems Unit Testing with Simpletest


I am using PHP and simpletest for unit testing. My tests work fine until I try and set the cookie

try{
    setcookie($name,$cookie,$cookie_expires );
}catch Exception($e){
  blah
}

The exception is thrown because simpletest has already written out header information so I get the following:

Unexpected PHP error [Cannot modify header information - headers already sent by (output started at /tests/simpletest/reporter.php:43)] severity [E_WARNING] in [blah_code.php line 280]

I've seen vague explanations on catching this with $this->expectException(new Exception()); but no further documentation or examples that work. Could someone provide a working example or point me to documentation? To be clear. This is NOT my code producing the output but rather SimpleTest.


Solution

  • One way to get around this is by using output buffering.

    You can turn it on globally in PHP's configuration (and possibly in .htaccess), or you can use ob_start() and its related functions (ob_get_clean(), ob_end_flush(), etc). For example:

    ob_start();
    // your SimpleTest here.
    // your header/ cookie manipulation here.
    

    And then:

    ob_end_clean(); // Stop buffering and dump everything (don't echo).
    ob_end_flush(); // Stop buffering and echo out the buffer.
    ob_get_clean(); // Stop buffering and return everything as a string.
    

    Or any of the other related functions. I believe PHP calls ob_flush() at the end of a file if you don't.