開始動手安裝phpunitphp
本文中將經過介紹php中的單元測試利器phpunit(http://phpunit.de/),並經過實際例子來說解如何在實際工做中運用phpunit。首先安裝phpunit的方法能夠經過php下的pear去安裝:html
pear channel-discover pear.phpunit.de pear channel-discover components.ez.no pear channel-discover pear.symfony-project.com pear install phpunit/PHPUnit
若是你想經過手動方式去安裝,能夠參考phpunit的手冊去安裝(http://www.phpunit.de/manual/3.0/en/installation.html)。正則表達式
編寫第一個單元測試用例php框架
下面咱們開始編寫第一個單元測試用例。在編寫測試用例時,要遵照以下的phpunit的規則:服務器
1 通常地,在測試用例中,能夠擴展PHPUnit_Framework_TestCase類,這樣就可使用象setUp(),tearDown()等方法了。app
2 測試用例的名字最好是使用約定俗成的格式,即在被測試類的後面加上」Test」,好比要測試的類爲RemoteConnect,則測試用例的命名爲RemoteConnectTest。框架
3 在一個測試用例中的全部的測試方法,在命名時都應該以test+測試方法名去命名,如testDoesLikeWaffles(),要注意的是該方法必須是聲明爲public類型的。固然能夠在你的測試用例中包含private的方法,但它們不能被phpunit所調用。單元測試
4 測試方法中是不能接收參數的。測試
下面首先舉個簡單的例子,代碼以下:ui
<?php class RemoteConnect { public function connectToServer($serverName=null) { if($serverName==null){ throw new Exception(「That's not a server name!」); } $fp = fsockopen($serverName,80); return ($fp) ? true : false; } public function returnSampleObject() { return $this; } } ?>
上面的代碼實際上是實現鏈接到一個指定的服務器的功能,那麼咱們能夠編寫測試代碼以下:
<?php require_once('RemoteConnect.php'); class RemoteConnectTest extends PHPUnit_Framework_TestCase { public function setUp(){ } public function tearDown(){ } public function testConnectionIsValid() { // test to ensure that the object from an fsockopen is valid $connObj = new RemoteConnect(); $serverName = 'www.google.com'; $this->assertTrue($connObj->connectToServer($serverName) !== false); } } ?>
在上面的代碼中,因爲繼承了PHPUnit_Framework_TestCase類,所以在setUp和tearDown方法中,不須要編寫任何代碼。SetUp方法是在每一個測試用例運行前進行一些初始化的工做,而tearDown則在每一個測試用例運行後進行一些好比資源的釋放等工做。在測試方法中,經過使用phpunit的斷言assertTrue去判斷所返回的布爾值是否爲真,這裏是經過調用RemoteConnect.php中的connectToServe方法去判斷可否鏈接上服務器。
接下來咱們運行這個單元測試,在命令行下輸入代碼:
phpunit /path/to/tests/RemoteConnectTest.php便可,能夠看到測試順利經過的話,會輸出如下結果:
PHPUnit 3.4 by Sebastian Bergmann . Time: 1 second Tests: 1, Assertions: 1, Failures 0
能夠看到,上面是經過了測試。默認狀況下,phpunit是會運行測試用例中的全部測試方法的。下面再介紹下phpunit中相關的幾個斷言:
AssertTrue/AssertFalse 斷言是否爲真值仍是假 AssertEquals 判斷輸出是否和預期的相等 AssertGreaterThan 斷言結果是否大於某個值,一樣的也有LessThan(小於),GreaterThanOrEqual(大於等於), LessThanOrEqual (小於等於). AssertContains 判斷輸入是否包含指定的值 AssertType 判斷是否屬於指定類型 AssertNull 判斷是否爲空值 AssertFileExists 判斷文件是否存在 AssertRegExp 根據正則表達式判斷
舉個例子來講明下好比AssertType的使用,依然以上面的例子來講,能夠用AssertType去判斷returnSampleObject返回的對象實例是否爲remoteConnect,代碼以下:
<?php function testIsRightObject() { $connObj = new RemoteConnect(); $returnedObject = $connObj->returnSampleObject(); $this->assertType('remoteConnect', $returnedObject); } ?>
目前PHP框架對單元測試的支持
目前不少優秀的php框架(如Zend Framework,Symfony等),都提供了對單元測試很好的支持。以Zend Framework爲例,說明下其中是如何運行單元測試的。
<?php class CommentControllerTest extends Zend_Test_PHPUnit_ControllerTestCase { public function setUp() { parent::setUp(); } public function tearDown() { parent::tearDown(); } public function appBootstrap()