When running a PHPUnit test, I would like to be able to dump output so I can debug one or two things.
I have tried the following (similar to the PHPUnit Manual examp
You should really think about your intentions: If you need the information now when debugging to fix the test, you will need it next week again when the tests break.
This means that you will need the information always when the test fails - and adding a var_dump
to find the cause is just too much work. Rather put the data into your assertions.
If your code is too complex for that, split it up until you reach a level where one assertion (with a custom message) tells you enough to know where it broke, why and how to fix the code.
Hackish, but works: Throw an exception with the debug output as its message.
class theTest extends PHPUnit_Framework_TestCase
{
public function testOutput() {
throw new \Exception("hello");
}
}
Yields:
...
There was 1 error:
1) theTest::testOutput
Exception: hello
UPDATE
Just realized another way to do this that works much better than the --verbose
command line option:
class TestSomething extends PHPUnit_Framework_TestCase {
function testSomething() {
$myDebugVar = array(1, 2, 3);
fwrite(STDERR, print_r($myDebugVar, TRUE));
}
}
This lets you dump anything to your console at any time without all the unwanted output that comes along with the --verbose
CLI option.
As other answers have noted, it's best to test output using the built-in methods like:
$this->expectOutputString('foo');
However, sometimes it's helpful to be naughty and see one-off/temporary debugging output from within your test cases. There is no need for the var_dump
hack/workaround, though. This can easily be accomplished by setting the --verbose
command line option when running your test suite. For example:
$ phpunit --verbose -c phpunit.xml
This will display output from inside your test methods when running in the CLI environment.
See: Writing Tests for PHPUnit - Testing Output.
If you use Laravel, then you can use logging functions such as info() to log to the Laravel log file under storage/logs. So it won't appear in your terminal but in the log file.
PHPUnit is hiding the output with ob_start()
. We can disable it temporarily.
public function log($something = null)
{
ob_end_clean();
var_dump($something);
ob_start();
}
You can use PHPunit default way of showing messages to debug your variables inside your test like this:
$this->assertTrue(false,$your_variable);