標籤:
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
[[email protected] phpunit_test]# phpunit --versionPHPUnit 5.6.1 by Sebastian Bergmann and contributors.
2.建立單元測試檔案
檔案名稱為UnitTest.php
我們可以在單元測試檔案內的方法裡面調用功能模組,用資料類比看是否運行正常,如果通則會報錯,斷掉
<?php class UnitTest extends PHPUnit_Framework_TestCase{ public function testPushAndPop(){ $stack = array(); $this->assertEquals(0,count($stack)); array_push($stack,‘foo‘); //斷言插入資料到$stack數組後值是否等於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運行檔案
[[email protected] phpunit_test]# phpunit UnitTest.php PHPUnit 5.6.1 by Sebastian Bergmann and contributors..F 2 / 2 (100%)Time: 82 ms, Memory: 6.75MBThere was 1 failure:1) UnitTest::indexEqualsFailed asserting that 1 matches expected 2./wwwroot/phpunit_test/UnitTest.php:18FAILURES!Tests: 2, Assertions: 3, Failures: 1.
結果顯示測試php檔案中共運行兩個模組,有一個模組錯誤
錯誤測試方法名為indexEquals報錯行為18行。
因為因為stack等於0不等於斷言的1,所以報錯,定位錯誤成功。
phpunit單元測試