本文實例講述了PHP使用phpunit進行單元測試。分享給大家供大家參考,具體如下:
1. linux服務器上安裝phpunit
1
2
3
|
wget https: //phar .phpunit.de /phpunit .phar chmod +x phpunit.phar sudo mv phpunit.phar /usr/local/bin/phpunit |
建立phpunit短命令
phpunit --version
1
2
|
[root@dongzi phpunit_test] # phpunit --version PHPUnit 5.6.1 by Sebastian Bergmann and contributors. |
2. 創建單元測試文件
文件名稱為UnitTest.php
我們可以在單元測試文件內的方法里面調用功能模塊,用數據模擬看是否運行正常,如果通則會報錯,斷掉
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<?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運行文件
1
2
3
4
5
6
7
8
9
10
|
[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程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/lisqiong/p/5964375.html