本文實(shí)例講述了PHP測(cè)試框架PHPUnit組織測(cè)試操作。分享給大家供大家參考,具體如下:
首先是目錄結(jié)構(gòu)
源文件夾為 src/
測(cè)試文件夾為 tests/
User.php
<?php class Errorcode { const NAME_IS_NULL = 0; } class User { public $name; public function __construct($name) { $this->name=$name; } public function Isempty() { try{ if(empty($this->name)) { throw new Exception('its null',Errorcode::NAME_IS_NULL); } }catch(Exception $e){ return $e->getMessage(); } return 'welcome '.$this->name; } }
對(duì)應(yīng)的單元測(cè)試文件 UserTest.php
<?php use PHPUnit\Framework\TestCase; class UserTest extends TestCase { protected $user; public function setUp() { $this->user = new User(''); } public function testIsempty() { $this->user->name='mark'; $result =$this->user->Isempty(); $this->assertEquals('welcome mark',$result); $this->user->name=''; $results =$this->user->Isempty(); $this->assertEquals('its null',$results); } }
第二個(gè)單元測(cè)試代碼因?yàn)橐?要測(cè)試的類 這里可以用 自動(dòng)載入 避免文件多的話 太多include
所以在src/ 文件夾里寫(xiě) autoload.php
<?php function __autoload($class){ include $class.'.php'; } spl_autoload_register('__autoload');
當(dāng)需要User類時(shí),就去include User.php
。寫(xiě)完__autoload()
函數(shù)之后要用spl_autoload_register()
注冊(cè)上。
雖然可以自動(dòng)載入,但是要執(zhí)行的命令變得更長(zhǎng)了。
打開(kāi)cmd命令如下
phpunit --bootstrap src/autoload.php tests/UserTest
所以我們還可以在根目錄寫(xiě)一個(gè)配置文件phpunit.xml來(lái)為項(xiàng)目指定bootstrap,這樣就不用每次都寫(xiě)在命令里了。
phpunit.xml
<phpunit bootstrap="src/autoload.php"> </phpunit>
然后
打開(kāi)cmd命令 執(zhí)行MoneyTest 命令如下
phpunit tests/UserTest
打開(kāi)cmd命令 執(zhí)行tests下面所有的文件 命令如下
phpunit tests
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。