扩展phpunit错误消息

时间:2011-07-31 22:46:46

标签: phpunit

我想将日志输出添加到所有测试消息中。

$this->assertTrue(FALSE, "This assertion is False.". myLog::GetErrors());

我尝试使用附加的消息扩展PHPUnit_Framework_TestCase :: assertThat函数,但它似乎没有对它产生影响。我知道扩展的PHPUnit_Framework_TestCase有效,因为我在那里有几个辅助函数(随机字符串生成),我用它来进行测试。

还有其他想法吗?它可以成为客户倾听者吗?

2 个答案:

答案 0 :(得分:2)

所有断言都是来自PHPUnit_Framework_Assert的静态方法,不能被TestCase的子类覆盖。但是,您可以使用修改后的消息定义自己的断言来调用原始文件。

public static function assertTrue($value, $message='') {
    PHPUnit_Framework_Assert::assertTrue($value, $message . myLog::GetErrors());
}

所有失败的测试都会调用onNotSuccessfulTest(),并将异常作为唯一参数。您可以覆盖此方法,并在某些情况下将日志错误添加到异常的消息中。除了异常中包含的错误消息之外,一些PHPUnit异常还提供了第二个描述。

public function onNotSuccessfulTest(Exception $e) {
    if ($e instanceof PHPUnit_Framework_ExpectationFailedException) {
        $e->setCustomMessage(implode(PHP_EOL, 
                array($e->getCustomMessage(), myLog::GetErrors())));
    }
    parent::onNotSuccessfulTest($e);
}

更新:正如Gregory Lo在下面的评论中所指出的,setCustomMessage()getCustomMessage()已在PHPUnit 3.6中删除。 :(

答案 1 :(得分:0)

在最近的PHPUnit版本中,不再需要了。 在$this->assertXXXX()中指定error参数时,它在PHPUnit的原始消息之前。

截图:

enter image description here