php與其他語言不太一樣,單元測試需要自己安裝和配置,相對麻煩一點,不過單元測試對於提高庫的穩定性和健壯性還是非常給力的,下面教大家怎么配置PHP單元測試
注意:php需升級到7.1版本以上
配置說明
1.全局安裝phpunit命令腳本
$ wget https://phar.phpunit.de/phpunit-7.0.phar $ chmod +x phpunit-7.0.phar $ sudo mv phpunit-7.0.phar /usr/local/bin/phpunit $ phpunit --version PHPUnit x.y.z by Sebastian Bergmann and contributors.
2.全局安裝安裝phpunit代碼
composer global require phpunit/phpunit
3.創建 phpunit.xml放在你的項目根目錄, 這個文件是 phpunit 會默認讀取的一個配置文件:
<phpunit bootstrap="vendor/autoload.php"> <testsuites> <testsuite name="service"> <directory>tests</directory> </testsuite> </testsuites> </phpunit>
4.配置phpstorm單元phpunit.phar路徑,Languages & Frameworks > PHP > PHPUinit
如我的phpunit本地的路徑為/usr/local/bin/phpunit
5.配置單元測試類提示,Languages & Frameworks > PHP > include path
如我的phpunit包本地的路徑為/Users/chenqionghe/.composer/vendor/phpunit
6.單元測試編寫
1.Class為Demo的測試類為DemoTest
2.測試類繼承於 PHPUnit\Framework\TestCase
3.測試方法
- 必須為public權限,
- 一般以test開頭,也可以給其加注釋@test來標識
- 在測試方法內,類似於 assertEquals() 這樣的斷言方法用來對實際值與預期值的匹配做出斷言。
<?php use Eoffcn\Utils\Arrays; use PHPUnit\Framework\TestCase; /** * Array測試用例 * Class ArraysTest */ class ArraysTest extends TestCase { public function testGet() { $array = [ 1 => [ 'b' => [ 'c' => 'cqh' ] ], 2 => [ 'b' => [ 'c' => 'cqh' ] ] ]; $this->assertEquals('cqh', Arrays::get($array, '1.b.c')); } }
執行單元測試
1.執行單個文件單元測試
Phpstorm方式,當前測試類右鍵Run即可
命令行的方式,進行項目目錄執行
phpunit tests/ArraysTest.php
2.執行全局單元測試
phpstorm方式
命令行方式,命令行下進入當前項目執行
phpunit