PHP使用phpunit進行單元測試示例
本文實例講述了PHP使用phpunit進行單元測試。分享給大家供大家參考,具體如下:
1. linux服務器上安裝phpunit
wget https://phar.phpunit.de/phpunit.phar chmod +x phpunit.phar sudo mv phpunit.phar /usr/local/bin/phpunit
建立phpunit短命令
phpunit --version
[root@dongzi phpunit_test]# phpunit --version PHPUnit 5.6.1 by Sebastian Bergmann and contributors.
2. 創(chuàng)建單元測試文件
文件名稱為UnitTest.php
我們可以在單元測試文件內(nèi)的方法里面調(diào)用功能模塊,用數(shù)據(jù)模擬看是否運行正常,如果通則會報錯,斷掉
<?php class UnitTest extends PHPUnit_Framework_TestCase{ public function testPushAndPop(){ $stack = array(); $this->assertEquals(0,count($stack)); array_push($stack,'foo'); //斷言插入數(shù)據(jù)到$stack數(shù)組后值是否等于1 $this->assertEquals(1,count($stack)); } /** *定義test標簽聲明該方法是測試方法 *@test ***/ public function indexEquals(){ $stack = array(1,2,3,4); //斷言$stack[0]等于2 $this->assertEquals(2,$stack[0]); } } ?>
3. phpunit運行文件
[root@dongzi phpunit_test]# phpunit UnitTest.php PHPUnit 5.6.1 by Sebastian Bergmann and contributors. .F 2 / 2 (100%) Time: 82 ms, Memory: 6.75MB There was 1 failure: 1) UnitTest::indexEquals Failed asserting that 1 matches expected 2. /wwwroot/phpunit_test/UnitTest.php:18 FAILURES! Tests: 2, Assertions: 3, Failures: 1.
結果顯示測試php文件中共運行兩個模塊,有一個模塊錯誤
錯誤測試方法名為indexEquals報錯行為18行。
因為因為stack等于0不等于斷言的1,所以報錯,定位錯誤成功。
更多關于PHP相關內(nèi)容感興趣的讀者可查看本站專題:《PHP錯誤與異常處理方法總結》、《php字符串(string)用法總結》、《PHP數(shù)組(Array)操作技巧大全》、《PHP運算與運算符用法總結》、《PHP網(wǎng)絡編程技巧總結》、《PHP基本語法入門教程》、《php面向對象程序設計入門教程》及《php優(yōu)秀開發(fā)框架總結》
希望本文所述對大家PHP程序設計有所幫助。
相關文章
phpmailer簡單發(fā)送郵件的方法(附phpmailer源碼下載)
這篇文章主要介紹了phpmailer簡單發(fā)送郵件的方法,提供了phpmailer的源碼與相應的設置、使用方法,需要的朋友可以參考下2016-06-06PHP提示W(wǎng)arning:phpinfo() has been disabled函數(shù)禁用的解決方法
這篇文章主要介紹了PHP提示W(wǎng)arning:phpinfo() has been disabled函數(shù)禁用的解決方法,涉及針對配置文件中禁用函數(shù)的修改技巧,非常具有實用價值,需要的朋友可以參考下2014-12-12php基于ob_start(ob_gzhandler)實現(xiàn)網(wǎng)頁壓縮功能的方法
這篇文章主要介紹了php基于ob_start('ob_gzhandler')實現(xiàn)網(wǎng)頁壓縮功能的方法,涉及php中ob_gzip、ob_start等函數(shù)操作緩沖區(qū)及內(nèi)容壓縮相關技巧,需要的朋友可以參考下2017-02-02