PHPUnit-hasOutput()不工作
我刚开始使用PHPUnit进行一些测试,在检测输出时遇到了问题。PHPUnit-hasOutput()不工作,php,testing,phpunit,Php,Testing,Phpunit,我刚开始使用PHPUnit进行一些测试,在检测输出时遇到了问题。 $this->hasOutput()返回false,即使我正在回显数据。我做错了什么?任何帮助都将不胜感激 class DatabaseTest extends PHPUnit_Framework_TestCase { public function testOutput() { SampleDB::echoOutput(); $result = $this->hasOutput()
$this->hasOutput()返回false,即使我正在回显数据。我做错了什么?任何帮助都将不胜感激
class DatabaseTest extends PHPUnit_Framework_TestCase
{
public function testOutput() {
SampleDB::echoOutput();
$result = $this->hasOutput() ? "true" : 'false';
echo $result;
}
. . .
实施:
class SampleDB {
public static function echoOutput(){
echo "hello world!";
}
运行测试:
phpunit DatabaseTest
PHPUnit 4.2.6 by Sebastian Bergmann.
.hello world!false.
Time: 55 ms, Memory: 1.75Mb
OK (2 tests, 0 assertions)
以下是我的PHPUnit版本的
hasOutput
的源代码(3.7.34,因此您的版本可能有所不同;如果确实如此,我下面的结论可能不适用于您的特定场景):
测试用例上的output
成员变量仅在测试执行(包括tearDown
)完成后填充,因此在测试执行时它将始终为空,因此hasOutput
将始终返回false
我不确定hasOutput的预期用途是什么,因为我在PHPUnit文档中找不到它。根据一些grepping,它看起来像是在严格模式打开时使用的,用于抱怨测试是否已完成,并且有未明确预期的输出
如果您需要根据测试是否有任何输出在测试中有条件地执行某些操作,您应该能够使用getActualOutput()
(这也是函数的3.7.x版本;可能在4中更改),它将返回当前缓冲的输出字符串
您还可以使用诸如expectOutputString()
之类的断言
e、 g
在这种情况下,断言将失败,因为测试的实际输出是helloworld!真的谢谢!我试图使用这个函数来查看我的代码是否输出了任何数据(即,确保它在回显某些输出)——但hasOutput实际上用于确定测试输出的数据是否有意义。
/**
* @return boolean
* @since Method available since Release 3.6.0
*/
public function hasOutput()
{
if (strlen($this->output) === 0) {
return FALSE;
}
if ($this->outputExpectedString !== NULL ||
$this->outputExpectedRegex !== NULL ||
$this->hasPerformedExpectationsOnOutput) {
return FALSE;
}
return TRUE;
}
public function testOutput() {
SampleDB::echoOutput();
$result = ($this->getActualOutput() != '') ? "true" : 'false';
$this->expectOutputString('hello world!');
echo $result;
}