用phpUnit帮你调试php程序
程序
调试程序是一个漫长的过程,程序越长越复杂,调试起来就愈加困难。如果你调试的是php程序,那么不妨采用phpUnit,它可以大大加快你的调试速度。
何谓PhpUnit
Phpunit 脱胎于Fred Yankowski编写的著名的Junit测试框架。你可以到它的网站 http://www.ontosys.com/phiki/phpunit 下载最新的版本。你可以利用phpUnit编写一套测试软件包。保证你的程序代码正确无误。只需一步便可自动完成所有的测试。
如果监测到bug,你就可以再写一小段测试代码来找出错误之所在。日后若再有相同的bug出现,只要运行你先前的测试包,马上就可以抓到它。经常运行测试包便可以保证你的程序代码的强壮性。
开 始
假设我们有一个银行账务处理程序。现在需要为Account (账户) 类编写一个测试软件包。
以下是Account类 源代码:
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类的源代码如下:
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类加入测试代码了。
// 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
function testDeposit(){
$this->_ac2->deposit(10);
$this->assertEquals(30,$this->_ac2->getBalance()); //20 +10 = 30
}
// Tranfers 10 units from _ac3 to _ac4
// _ac3's initial balance is 30
// _ac4's initial balance is 50
function testTransferFrom(){
$this->_ac4->transferFrom(&$this->_ac3,10);
$this->assertEquals(20,$this->_ac3->getBalance(),"Source account balance incorrect"); // 30 - 10 = 20
$this->assertEquals(60,$this->_ac4->getBalance(),"Target account balance incorrect"); // 50 + 10 = 60
}
?>
这段代码中,assert(如同C里的断言)方法是测试的关键部分。如果在assert中的条件表达式为真,那么测试通过。否则返回错误。由于assert方法大都用于判断两个变量的值是否相等。因此,testclass类引入了assertEquals方法专门实现这个功能。AssertEquals方法中有3个参数,依次分别为:期望值,测试值,两值不相等时返回的消息提示串。
运行测试过程
好了,现在可以运行一下我们编好的测试程序了。我们还必须建立一个runtest.php测试程序来运行所有的测试过程。
runtest.php源代码如下:
$tSuite = new TestSuite(); //creation of the test suite object 创建测试套件对象
$tSuite->addtest(new AccountTester("testWithdraw")); //Add inidividual tests
$tSuite->addtest(new AccountTester("testDeposit")); //加入专门测试方法。
$tSuite->addtest(new AccountTester("testTransferFrom"));
$res = new TextTestResult(); //Creation of the Result 建立一个测试结果类
$tSuite->run(&$res); //Run of the test 运行测试
$res->report(); //Print results 输出测试结果。
?>
程序说明:
首先创建测试套件对象tSuite,然后逐一加入专门测试方法,addtest方法的参数是测试方法的 再创建测试报告对象,随之运行测试。测试发现错误的结果由TestResult类捕捉,TestResult可以定制一套text/html的错误报告。如果有必要你也可以自己编写输出部分。测试结果封装在TestResult类中,为了输出测试结果。我们采用了phpUnit提供的另外一个类TextTestResult类,它可以输出文本或超文本格式的报告。当然我们也可以自己定制一个新的TestResult的子类控制更复杂的输出格式。
提示和技巧
1、在编写一个新的测试套件完成之后,我们可以先引入一个小小的bug以证明测试套件可以正常运行。
比如,在本例account类中,我们故意引入一个有问题的函数。
function withdraw($amount){
$this->balance -= $Amount;
// 变量名大小写错误,本意是调用$amount参数,结果引入一个新变量$Amount。
}
?>
好,现在让我们运行测试套件,如果不出意外的话,我们将很快发现错误之处。
2.要指出的是,并非所有的方法都需要测试。你只需对相关的方法进行测试。
3.如果在开始编码前就写好测试代码,会使你更进一步明白你的程序到底需要完成什么样的任务。
现在,通过引入phpUnit的测试套件类,你可以发现找bug的时间缩短了,而你作为一个程序员的工作效率也提高了。
那么,尽情享受抓虫子的乐趣吧。祝您好胃口。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Function means function. It is a reusable code block with specific functions. It is one of the basic components of a program. It can accept input parameters, perform specific operations, and return results. Its purpose is to encapsulate a reusable block of code. code to improve code reusability and maintainability.

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

In this article, we will learn about enumerate() function and the purpose of “enumerate()” function in Python. What is the enumerate() function? Python's enumerate() function accepts a data collection as a parameter and returns an enumeration object. Enumeration objects are returned as key-value pairs. The key is the index corresponding to each item, and the value is the items. Syntax enumerate(iterable,start) Parameters iterable - The passed in data collection can be returned as an enumeration object, called iterablestart - As the name suggests, the starting index of the enumeration object is defined by start. if we ignore

Detailed explanation of the role and function of the MySQL.proc table. MySQL is a popular relational database management system. When developers use MySQL, they often involve the creation and management of stored procedures (StoredProcedure). The MySQL.proc table is a very important system table. It stores information related to all stored procedures in the database, including the name, definition, parameters, etc. of the stored procedures. In this article, we will explain in detail the role and functionality of the MySQL.proc table
