phpunit 單元測試之代碼覆蓋率

最近在不斷完善項目中的單元測試用例,會用到代碼覆蓋率分析,原本覺得 homestead 應該默認安裝了 xdebug ,因此使用 phpunit --coverage-html ./tests/codeCoverage 來生成 html 報告,可是執行後提示以下錯誤php

Error:         No code coverage driver is available

這是由於沒有安裝或啓用 xdebug 致使。html

我的環境:ubuntu

PHP 7.2.0-1+ubuntu16.04.1 + Homestead單元測試

install xdebug

$ wget https://xdebug.org/files/xdebug-2.6.0.tgz
$ tar xvzf xdebug-2.6.0.tgz
$ cd xdebug-2.6.0
$ phpize7.2
$ ./configure --enable-xdebug
$ make
$ sudo make install

enable xdebug for php

find /usr/ -name "xdebug.so"
/usr/lib/php/20170718/xdebug.so  //剛剛安裝的 xdebug 2.6.0 版本
/usr/lib/php/20131226/xdebug.so
/usr/lib/php/20160303/xdebug.so
/usr/lib/php/20151012/xdebug.so
vi /etc/php/7.2/cli/php.ini

添加以下代碼到 php.ini 結尾處測試

zend_extension="/usr/lib/php/20170718/xdebug.so"
xdebug.remote_enable = 1
xdebug.remote_connect_back = 1
xdebug.remote_port = 9000
xdebug.max_nesting_level = 500

build code coverage report

有兩種方法:ui

1.直接執行 phpunit --coverage-html ./tests/codeCoverage 命令 2.在 phpunit.xml 添加以下代碼:debug

<logging>
   <log type="coverage-html" target="./tests/codeCoverage" charset="UTF-8"/>
</logging>

而後直接執行 phpunit 便可。code

完成會在 tests/codeCoverage 目錄下生成 html 報告,以下所示:xml

clipboard.png

經過這樣的分析,可以更好的幫助咱們完善單元測試,保證代碼測試的完整性,也能讓咱們的代碼更加健壯。htm

討論交流

iBrand聯繫咱們

相關文章
相關標籤/搜索