PHP Unit Testing Fundamentals

From Littledamien Wiki
Revision as of 21:26, 29 February 2024 by Video8 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Capturing the output buffer[edit]

One scenario is checking the output of a routine that sends processed template content directly to the output buffer.

ob_start();

// Something that writes to the output buffer
$obj->processTemplate();

// capture output buffer content
$response = json_decode(ob_get_contents());
ob_end_clean();

// test the content
self::assertEquals('some value', $response->some_field);

The problem arises that PHPUnit will send its own output to the output buffer causing a "Headers have already been written" error when the test attempts to write to the output buffer.

Solution[edit]

Run the test with the --stderr option, e.g. phpunit --stderr.

Note that another solution is to use the @runInSeparateProcess annotation for the test. This option will often work fine for single tests, or several tests within a class.

There are two problems with @runInSeparateProcess however. One is that the debugger can't follow processing into the process that gets forked off for the test. Another is that if many tests in multiple classes use the annotation, PHP sessions can interfere with each other or do unexpected things. The global PHP state becomes different than it was when running the tests singly, and the debugger can't be used to determine the cause.

Links[edit]

Notes[edit]