本文實例講述了PHP測試框架PHPUnit組織測試操作。分享給大家供大家參考,具體如下:
首先是目錄結(jié)構(gòu)
源文件夾為 src/
測試文件夾為 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; } }
對應(yīng)的單元測試文件 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); } }
第二個單元測試代碼因為要引入 要測試的類 這里可以用 自動載入 避免文件多的話 太多include
所以在src/ 文件夾里寫 autoload.php
<?php function __autoload($class){ include $class.'.php'; } spl_autoload_register('__autoload');
當(dāng)需要User類時,就去include User.php
。寫完__autoload()
函數(shù)之后要用spl_autoload_register()
注冊上。
雖然可以自動載入,但是要執(zhí)行的命令變得更長了。
打開cmd命令如下
phpunit --bootstrap src/autoload.php tests/UserTest
所以我們還可以在根目錄寫一個配置文件phpunit.xml來為項目指定bootstrap,這樣就不用每次都寫在命令里了。
phpunit.xml
<phpunit bootstrap="src/autoload.php"> </phpunit>
然后
打開cmd命令 執(zhí)行MoneyTest 命令如下
phpunit tests/UserTest
打開cmd命令 執(zhí)行tests下面所有的文件 命令如下
phpunit tests
希望本文所述對大家PHP程序設(shè)計有所幫助。