- 论坛徽章:
- 0
|
第 8 章 测试用例扩展
PHPUnit提供了用于测试类的标准基类PHPUnit_Framework_TestCase的扩展,这有助于编写用于输出和性能衰退的测试。
测试输出
有时候会想要断定方法的执行情况,比如期望产生怎样的输出(例如通过echo或print)。类PHPUnit_Extensions_OutputTestCase使用PHP的
输出缓冲
特性提供此处所需的功能。
范例 8.1
显示如何继承PHPUnit_Extensions_OutputTestCase并用它的expectOutputString()方法设置期望的输出。如果未产生期望的输出,测试将被定为失败。
范例 8.1: 使用PHPUnit_Extensions_OutputTestCase
require_once 'PHPUnit/Extensions/OutputTestCase.php';
class OutputTest extends PHPUnit_Extensions_OutputTestCase
{
public function testExpectFooActualFoo()
{
$this->expectOutputString('foo');
print 'foo';
}
public function testExpectBarActualBaz()
{
$this->expectOutputString('bar');
print 'baz';
}
}
?>
phpunit OutputTest
PHPUnit 3.2.10 by Sebastian Bergmann.
.F
Time: 0 seconds
There was 1 failure:
1) testExpectBarActualBaz(OutputTest)
Failed asserting that two strings are equal.
expected string
difference
got string
FAILURES!
Tests: 2, Failures: 1.
表 8.1
PHPUnit_Extensions_OutputTestCase提供的方法。
表 8.1. OutputTestCase
方法含义void expectOutputRegex(string $regularExpression)设定期望值为输出匹配$regularExpression。void expectOutputString(string $expectedString)设定期望值为输出同$expectedString一样。bool setOutputCallback(callable $callback)设定回调方法,例如用于规格化实际输出。测试性能
你可以让测试类扩展自PHPUnit_Extensions_PerformanceTestCase,以便可以测试(例如)函数或方法的运行是否超过指定的时间限制。
范例 8.2
显示如何继承PHPUnit_Extensions_PerformanceTestCase并用它的setMaxRunningTime()方法设定测试的最大运行时间。如果测试运行时间不在该时间限制以内,则被定为失败。
范例 8.2: 使用PHPUnit_Extensions_PerformanceTestCase
require_once 'PHPUnit/Extensions/PerformanceTestCase.php';
class PerformanceTest extends PHPUnit_Extensions_PerformanceTestCase
{
public function testPerformance()
{
$this->setMaxRunningTime(2);
sleep(1);
}
}
?>
表 8.2
显示PHPUnit_Extensions_PerformanceTestCase提供的方法。
表 8.2. PerformanceTestCase
方法含义void setMaxRunningTime(int $maxRunningTime)设定测试的最大运行时间为$maxRunningTime(单位:秒)。integer getMaxRunningTime()返回测试允许的最大运行时间。
还有两个PHPUnit_Framework_TestCase的扩展,PHPUnit_Extensions_Database_TestCase和PHPUnit_Extensions_SeleniumTestCase,它们分别在
第 9 章
和
第 19 章
中有所涉及。
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/57558/showart_509392.html |
|