本文實(shí)例講述了PHP單元測試PHPUnit簡單用法。分享給大家供大家參考,具體如下:
windows開發(fā)環(huán)境下,PHP使用單元測試可以使用PHPUnit。
安裝
首先下載PHPUnit,官網(wǎng):https://phpunit.de/ 根據(jù)自己的PHP版本下載對應(yīng)的PHPUnit版本,我本地是PHP5.5,所以這里我下載PHPUnit4.8。下載完成得到phpunit-4.8.35.phar文件,放到任意目錄,這邊我放到D:\phpunit下,并把文件名改為:phpunit.phar 。配置環(huán)境變量:右擊我的電腦-》屬性-》高級系統(tǒng)設(shè)置-》環(huán)境變量-》編輯path在最后添加phpunit.phar的路徑,這里我是D:\phpunit,所以在最后添加D:\phpunit 。
打開命令行win+R輸入cmd,進(jìn)入到D:\phpunit
cd /d D:\phpunit
安裝phpunit
echo @php "%~dp0phpunit.phar" %* > phpunit.cmd
查看是否安裝成功
phpunit --version
如果顯示phpunit的版本信息,說明安裝成功了,這邊我顯示:PHPUnit 4.8.35 by Sebastian Bergmann and contributors.
測試
先寫一個需要測試的類,該類有一個eat方法,方法返回字符串:eating,文件名為Human.php
<?php class Human { public function eat() { return 'eating'; } }
再寫一個phpunit的測試類,測試Human類的eat方法,必須引入Human.php文件、phpunit,文件名為test1.php
<?php include 'Human.php'; use PHPUnit\Framework\TestCase; class TestHuman extends TestCase { public function testEat() { $human = new Human; $this->assertEquals('eating', $human->eat()); } } ?>
其中assertEquals方法為斷言,判斷eat方法返回是否等于'eating',如果返回一直則成功否則返回錯誤,運(yùn)行測試:打開命令行,進(jìn)入test1.php的路徑,然后運(yùn)行測試:
phpunit test1.php
返回信息:
PHPUnit 4.8.35 by Sebastian Bergmann and contributors.
.
Time: 202 ms, Memory: 14.75MB
OK (1 test, 1 assertion)
則表示斷言處成功,即返回值與傳入的參數(shù)值一致。
希望本文所述對大家PHP程序設(shè)計有所幫助。