问题
I have been trying to echo
stuff in my phpunit tests but no luck so far.
I read the documentation about the xml config file and apparently the debug
parameter is what I am looking for. Unfortunately it still doesn't work. Anyhow here is my xml config file:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit colors="true"
processIsolation="true"
verbose="true"
debug="true">
</phpunit>
Both processIsolation
and verbose
are accepted but debug
is not.
The command actually works pretty fine when I directly pass it to phpunit like this:
phpunit --debug MyTest.php # here stuff is echoed correctly
but with the xml config file it looks like it is ignored.
回答1:
Current versions of PHPUnit >3.6.4
(and all 3.5.*
versions) will just print everything you echo
in a test case.
<?php
class OutputTestCase extends PHPUnit_Framework_TestCase {
public function testEcho() {
echo "Hi";
}
}
produces:
phpunit foo.php
PHPUnit 3.6.7 by Sebastian Bergmann.
.Hi
Time: 0 seconds, Memory: 3.25Mb
OK (1 test, 0 assertions)
So if you are on an old 3.6
version just upgrade :)
回答2:
Make sure you don't call exit() or kill(). PHPUnit buffers the echo statements and that buffer will be lost with no output if your script exits during the test.
回答3:
processIsolation
is suppressing the output of tests so you have to disable it.
The interaction with the debug
flag was probably an oversight introduced with this:
https://github.com/sebastianbergmann/phpunit/pull/1489
回答4:
In case your test takes a long time and you would like to see the output during the process, add the following method to your test class:
protected function prontoPrint($whatever = 'I am printed!')
{
// if output buffer has not started yet
if (ob_get_level() == 0) {
// current buffer existence
$hasBuffer = false;
// start the buffer
ob_start();
} else {
// current buffer existence
$hasBuffer = true;
}
// echo to output
echo $whatever;
// flush current buffer to output stream
ob_flush();
flush();
ob_end_flush();
// if there were a buffer before this method was called
// in my version of PHPUNIT it has its own buffer running
if ($hasBuffer) {
// start the output buffer again
ob_start();
}
}
Now whenever you call $this->prontoPrint($variable)
inside your test class, it will immediately show the text in the console. I used this php.net comment to write the function.
PHPUnit 5.7.21
PHP 5.6.31 with Xdebug 2.5.5
来源:https://stackoverflow.com/questions/8790271/echo-in-phpunit-tests