用phpunit調試PHP程序

發表于:2009-05-20來源:作者:點擊數: 標簽:PHPUnitphpunit調試phpPHP
調試程序是一個漫長的過程,程序越長越復雜,調試起來就愈加困難。如果你調試的是 php 程序,那么不妨采用 phpUnit ,它可以大大加快你的調試速度。 何謂PhpUnit Phpunit 脫胎于Fred Yankowski編寫的著名的 Junit 測試 框架。你可以到它的網站http://www.ont
  調試程序是一個漫長的過程,程序越長越復雜,調試起來就愈加困難。如果你調試的是php程序,那么不妨采用phpUnit,它可以大大加快你的調試速度。
何謂PhpUnit
        Phpunit 脫胎于Fred Yankowski編寫的著名的Junit測試框架。你可以到它的網站http://www.ontosys.com/phiki/phpunit下載最新的版本。你可以利用phpUnit編寫一套測試軟件包。保證你的程序代碼正確無誤。只需一步便可自動完成所有的測試。
        如果監測到bug,你就可以再寫一小段測試代碼來找出錯誤之所在。日后若再有相同的bug出現,只要運行你先前的測試包,馬上就可以抓到它。經常運行測試包便可以保證你的程序代碼的強壯性。
開 始
        假設我們有一個銀行賬務處理程序?,F在需要為Aclearcase/" target="_blank" >ccount (賬戶) 類編寫一個測試軟件包。
以下是Account類 源代碼:
<?php
 
class Account{
var $balance;
function Account($initialBalance=0){
$this->balance = $initialBalance;
}
function withdraw($amount){
$this->balance -= $amount;
}
function deposit($amount){
$this->balance += $amount;
}
function getBalance(){
return $this->balance;
}
function transferFrom(&$sourceAccount,$amount){
$sourceAccount->withdraw($amount);
$this->deposit($amount);
}
?>
 
創建一個測試類
 
        首先,我們建立一個測試類AccountTest,它是一個由PhpUnit提供的TestCase的子類。在這個TestCase類中有2個基本的方法: setUp和tearDown。 這2個方法的實現在父類中是空過程,必須由我們自己去重載。其中SetUp 用于進行AccountTest類的初始化處理。在本例中,我們對一些在測試中用到的賬號進行初始化。tearDown 則用于AccountTest類的清空處理,在本例中無需使用。因此,就不對它進行重載。這樣AccountTester類的源代碼如下:
 
<?php
 
class AccountTester extends TestCase{
var $_ac1;
var $_ac2;
var $_ac3;
var $_ac4;
 
function AccountTester($name){
$this->TestCase($name); // call parent constructor
}
function setUp(){
$this->_ac1 = new Account(100); // data for testWithdraw
$this->_ac2 = new Account(20); // data for testDeposit
$this->_ac3 = new Account(30); // data for testTransferFrom
$this->_ac4 = new Account(50);
}
}
?>
 
加入專門的測試代碼
        現在,我們可以往向AccountTester類加入測試代碼了。
 
<?php
 
// Make a withdrawal of 25 units from _ac1.
// _ac1's initial balance is 100
 
function testWithdraw(){
$this->_ac1->withdraw(25);
$this->assert($this->_ac1->getBalance() == 75); // 100 - 25 = 75
}
 
// Make a deposit of 10 units into _ac2.
// _ac1's initial balance is 20
 

原文轉自:http://www.anti-gravitydesign.com

国产97人人超碰caoprom_尤物国产在线一区手机播放_精品国产一区二区三_色天使久久综合给合久久97