牛骨文教育服务平台(让学习变的简单)

对输出进行测试

有时候,想要断言(比如说)某方法的运行过程中生成了预期的输出(例如,通过 echoprint)。PHPUnit_Framework_TestCase 类使用 PHP 的 输出缓冲 特性来为此提供必要的功能支持。

Example 2.16, “对函数或方法的输出进行测试”展示了如何用 expectOutputString() 方法来设定所预期的输出。如果没有产生预期的输出,测试将计为失败。

Example 2.16. 对函数或方法的输出进行测试

<?php
class OutputTest extends PHPUnit_Framework_TestCase
{
    public function testExpectFooActualFoo()
    {
        $this->expectOutputString("foo");
        print "foo";
    }

    public function testExpectBarActualBaz()
    {
        $this->expectOutputString("bar");
        print "baz";
    }
}
?>
phpunit OutputTest
PHPUnit 5.0.0 by Sebastian Bergmann and contributors.

.F

Time: 0 seconds, Memory: 5.75Mb

There was 1 failure:

1) OutputTest::testExpectBarActualBaz
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-"bar"
+"baz"

FAILURES!
Tests: 2, Assertions: 2, Failures: 1.

Table 2.2, “用于对输出进行测试的方法”中列举了用于对输出进行测试的各种方法。

Table 2.2. 用于对输出进行测试的方法

方法 含义
void expectOutputRegex(string $regularExpression) 设置输出预期为输出应当匹配正则表达式 $regularExpression
void expectOutputString(string $expectedString) 设置输出预期为输出应当与 $expectedString 字符串相等。
bool setOutputCallback(callable $callback) 设置回调函数,用来做诸如将实际输出规范化之类的动作。

Note

在严格模式下,本身产生输出的测试将会失败。