【问题标题】:PHPUnit - hasOutput() not workingPHPUnit - hasOutput() 不工作
【发布时间】:2014-10-06 03:15:38
【问题描述】:

我刚刚开始使用 PHPUnit 进行一些测试,但无法检测输出。
$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)

【问题讨论】:

    标签: php testing phpunit


    【解决方案1】:

    这是我的 PHPUnit 版本中hasOutput 的来源(3.7.34,因此您的可能有所不同;如果确实如此,我下面的结论可能不适用于您的特定场景):

    /**
     * @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;
    }
    

    测试用例上的output 成员变量仅在测试执行(包括tearDown)完成后才会填充,因此在执行测试时它始终为空,因此hasOutput 将始终返回false。

    我不确定hasOutput 的预期用途是什么,因为我在 PHPUnit 文档中找不到它。根据一些 grepping,它看起来像是在开启严格模式时用于抱怨测试是否已完成并且具有未明确预期的输出。

    如果您需要根据测试是否有任何输出在测试中有条件地做某事,您应该能够使用getActualOutput()(同样是该函数的 3.7.x 版本;可能在 4 中更改)这将返回当前缓冲的输出字符串。

    您还可以使用expectOutputString() 之类的断言。

    例如

        public function testOutput() {
                SampleDB::echoOutput();
                $result = ($this->getActualOutput() != '') ? "true" : 'false';
                $this->expectOutputString('hello world!');
                echo $result;
        }
    

    在这种情况下,断言会失败,因为测试的实际输出是'helloworld!true'

    【讨论】:

    • 谢谢!我试图使用这个函数来查看我的代码是否正在输出任何数据(即确保它正在回显某些输出)——但 hasOutput 实际上用于确定测试输出的数据是否......有意义。
    猜你喜欢
    • 2011-12-11
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2016-04-08
    相关资源
    最近更新 更多