设置场景
创建数组fixtures
[php]
protected function setup()
{
// 创建数组fixture。
$this->fixture = array();
}
“套件级装配器” 共享fixture即sharedfixture
phpunit_framework_testsuite对象的$sharedfixture属性在phpunit_framework_testsuite对象集合及phpunit_framework_testcase对象中都可用。
[php]
protected function setup()
{
$this->sharedfixture = new pdo(
'mysql:host=wopr;dbname=test',
'root',
''
);
}
provider数据提供者
使用数据提供者
组织测试套件
phpunit框架的phpunit_framework_testsuite类允许我们将一些测试组织在若干测试套件构成的一个层次结构中。让我们通过一个例子看看phpunit特有的测试套件。
范例 7.1显示一个删节版本的tests/alltests.php,范例 7.2显示一个删节版本的tests/framework/alltests.php。
第一级:
[php]
addtest(framework_alltests::suite());
// ...
return $suite;
}
}
if (phpunit_main_method == 'alltests::main') {
alltests::main();
}
?>
第二级:
[php]
addtestsuite('framework_asserttest');
// ...
return $suite;
}
}
if (phpunit_main_method == 'framework_alltests::main') {
framework_alltests::main();
}
?>
第三级:
[php]
assertequals(0, sizeof($fixture));
}
public function testarraycontainsanelement()
{
// 创建数组fixture。
$fixture = array();
// 向数组fixture增加一个元素。
$fixture[] = 'element';
//断言数组fixture的尺寸是1。
$this->assertequals(1, sizeof($fixture));
}
}
?>
类framework_asserttest是个扩展了phpunit_framework_testcase的标准测试用例。
运行tests/alltests.php则使用textui测试启动器运行全部测试,然而运行tests/framework/alltests.php则只运行类phpunit_framework_*的测试。
套件级装配器
类phpunit_framework_testsuite提供两个模板方法,setup()和teardown(),它们分别在测试套件的首个测试前和最后测试后被调用。
[php]
未完成和跳过的测试
public function testsomething()
{
}
如果我们分别将成功的测试和失败的必做绿灯和红灯,我们还需要黄灯标记未完成或未实现的测试。phpunit_framework_incompletetest是个标记接口,用于标记当测试结果为未完成或当前未实现时引发的异常。
[php]
asserttrue(true, 'this should already work.');
// 在这儿停住并将测试标记为未完成。
$this->marktestincomplete(
'this test has not been implemented yet.'
);
}
}
?>
跳过的测试
特定的环境中并非所有的测试都能运行。考虑个例子,一个具有多个驱动以支持不同数据库系统的数据库提取层。mysql驱动的测试当然只能在mysql服务器上运行。 $this->marktestskipped
[php]
marktestskipped(
'the mysqli extension is not available.'
);
}
}
public function testconnection()
{
// ...
}
}
?>
phpunit_framework_testresult
当你在运行所有这些测试时,你需要在某处存储所有结果:运行了多少测试,哪个失败了,以及他们耗时多久。
phpunit自带两个具体的测试装饰者:phpunit_extensions_repeatedtest和phpunit_extensions_testsetup。前一个用于重复运行一个测试,并且只当所有迭代都成功时才算成功。后面一个在第 6 章中讨论过。
要定制phpunit_framework_testresult,没必要编写它的整个子类。大多时候,实现一个新phpunit_framework_testlistener(见表 22.14)并在运行测试前附在phpunit_framework_testresult对象上就够了。
范例 23.4: 运行和观测测试套件
[php] www.2cto.com
addlistener(new simpletestlistener);
// 运行测试。
$suite->run($result);
?>
http://www.bkjia.com/phpjc/477859.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/477859.htmltecharticle设置场景 创建数组fixtures [php] protected function setup() { // 创建数组fixture。 $this-fixture = array(); } 套件级装配器 共享fixture即sharedfixture phpunit_f...