1、markTestSkipped和markTestIncomplete 在phpunit中,有兩個(gè)有用的方法markTestSkipped和markTestIncomplete。它們能允許你編寫(xiě)的單元測(cè)試中不單是只有通過(guò)和失敗兩種結(jié)果。markTestSkipped能讓phpUNIT不去執(zhí)行某個(gè)已經(jīng)編寫(xiě)好的測(cè)試方法。舉個(gè)例子說(shuō)明,比如下面的程序:
<?php
public function testThisMightHaveADb()
{
$myObject->createObject();
try {
$db = new Database();
$this->assertTrue($db->rowExists());
} catch (DatabseException $e) {
$this->markTestSkipped('This test was skipped because there was a database problem');
}
}
?> 在上面的程序中,是一個(gè)連接數(shù)據(jù)庫(kù)后,判斷數(shù)據(jù)是否存在的測(cè)試方法,但如果考慮數(shù)據(jù)庫(kù)的連接異常的話(huà),則應(yīng)該在拋出異常時(shí),使用markTestSkipped指出該測(cè)試方法應(yīng)該是被忽略的,因?yàn)槌霈F(xiàn)了異常,而注意的時(shí),此時(shí)有可能你寫(xiě)的代碼是正確的,只不過(guò)是出現(xiàn)了異常而已,這樣phpunit在輸出時(shí)就不會(huì)只是簡(jiǎn)單的輸出fail。
而markTestIncomplete也有點(diǎn)類(lèi)似,但有點(diǎn)不同的是,它是當(dāng)開(kāi)發(fā)者在編寫(xiě)一個(gè)未完成的測(cè)試方法時(shí)使用的,標(biāo)記出某個(gè)測(cè)試方法還沒(méi)編寫(xiě)完成,同樣測(cè)試結(jié)果也不會(huì)是fail,只是告訴phpunit這個(gè)測(cè)試方法還沒(méi)編寫(xiě)完成而已,例子如下:
<?php
public function testAreNotEnoughHours()
{
$this->markTestIncomplete("There aren't enough hours in the day to have my tests go green");
$trueVariable = true;
$this->assertTrue($trueVariable);
}
?> 2、更深入了解phpunit中的斷言
在上一篇文章中,已經(jīng)基本講解了一些基本的phpunit中的斷言的使用,這里以一個(gè)例子,下面是一個(gè)類(lèi)的代碼:
<?php
class Testable
{
public $trueProperty = true;
public $resetMe = true;
public $testArray = array(
'first key' => 1,
'second key' => 2
);
private $testString = "I do love me some strings";
public function __construct()
{
}
public function addValues($valueOne,$valueTwo) {
return $valueOne+$valueTwo;
}
public function getTestString()
{
return $this->testString;
}
}
?> 我們編寫(xiě)的單元測(cè)試代碼初步的框架如下:
<?php
class TestableTest extends phpUnit_Framework_TestCase
{
private $_testable = null;
public function setUp()
{
$this->_testable = new Testable();
}
public function tearDown()
{
$this->_testable = null;
}
/** test methods will go here */
}
?> 在上一篇文章中,已經(jīng)介紹了setUp方法和tearDown方法,這里的setUp方法中,建立了Testable()實(shí)例并保存在變量$_testable中,而在tearDown方法中,銷(xiāo)毀了該對(duì)象。
接下來(lái),開(kāi)始編寫(xiě)一些斷言去測(cè)試,首先看assertTrue和assertFalase:
<?php
public function testTruePropertyIsTrue()
{
$this->assertTrue($this->_testable->trueProperty,"trueProperty isn't true");
}
public function testTruePropertyIsFalse()
{
$this->assertFalse($this->_testable->trueProperty, "trueProperty isn't false");
}
?>
php技術(shù):PHP單元測(cè)試?yán)?PHPUNIT深入用法(二)第1/2頁(yè),轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。