As the title states, I’m looking forward to finding a way to prevent the error_log()
message to be printed in the terminal during my PHPUnit
tests.
In the example above, the method under test passes through an error_log(‘Don’t show up’), printing its message between the tests.
Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn’t a simple string).
Advertisement
Answer
Is there any way to prevent this behavior, to keep my test log fancy? Also, is there any way to catch the message and test its output? (for the cases where the message isn’t a simple string).
First of all what you see is not the test log. The error message that is displayed is actually on the standard error stream and not the standard output stream. For what you see this makes not much of a difference as the terminal shows both intermixed, logging to file would not log that error message.
This is b/c error_log()
writes the error message to the configured logfile (PHP’s error_log
ini directive). As Phpunit runs with the CLI version of PHP (on the command-line), this by default is the said standard error stream.
This also contains all needed information to not output to the standard error stream but to capture it, e.g. temporarily for a test:
$capture = tmpfile(); $saved = ini_set('error_log', stream_get_meta_data($capture)['uri']); error_log("Test for this message"); ini_set('error_log', $saved); var_dump(stream_get_contents($capture));
This will provide the contents output via error_log()
and via a temporary file:
string(59) "[06-Jul-2017 12:14:45 Europe/Amsterdam] Test for this message "
The temporary file is removed automatically when the test-case ends.