預先準備(brew 安裝的情況下)
- php7
- php7-xdebug
- runkit7
報錯資訊1:
Error:No code coverage driver is available
問題和解決:
# 沒有成功安裝xdebug
brew search php70-xdebug
brew install php70-xdebug
brew services restart php70
# 檢視php -v 如果資訊如下則安裝成功
PHP 7.0.25 (cli) (built: Oct 27 2017 12:56:53) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies with
Xdebug v2.5.5, Copyright (c) 2002-2017, by Derick Rethans
報錯資訊2:
Error: No whitelist configured, no code coverage will be generated
問題和解決:
# 因為我需要測試覆蓋率,而這裡沒有設定白名單,可以在專案目錄下增加 phpunit.xml,xml中增加下面這寫程式碼,
可以增加多個目錄。
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./Api1</directory>
</whitelist>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./Api2</directory>
</whitelist>
</filter>
報錯資訊3:
. 1 / 1 (100%)
Time: 340 ms, Memory: 10.00MB
OK (1 test, 0 assertions)
問題和解決:
# 測試其實已經通過了,但 0 assertions,代表沒有任何斷言被執行。
增加(或修改) processIsolation="false" 這行到 phpunit.xml 的 <phpunit >中
<phpunit
bootstrap="./tests/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
stopOnError="false"
stopOnIncoplete="false"
stopOnSkipped="false"
>
--process-isolation
每個測試都在獨立的PHP程式中執行。
下面貼上完整的phpunit.xml,配置項詳見:
<?xml version="1.0" encoding="UTF-8"?>
<!-- bootstrap 可以使用專案的autoload檔案 -->
<phpunit
bootstrap="./tests/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
stopOnError="false"
stopOnIncoplete="false"
stopOnSkipped="false"
>
<!-- testsuites 指定測試目錄集-->
<testsuites>
<testsuite name="Api Tests">
<directory suffix="Test.php">./tests/Api</directory>
</testsuite>
<testsuite name="Util Tests">
<directory suffix="Test.php">./tests/Util</directory>
</testsuite>
</testsuites>
<!-- 覆蓋率的測試檔案,blacklist 黑名單(不需要統計覆蓋率的檔案),whitelist 白名單(統計覆蓋率的測試檔案) 當黑名單與白名單檔案重複時,白名單起作用 -->
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./Util</directory>
</whitelist>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./Api</directory>
</whitelist>
</filter>
<!-- 生成單元測試覆蓋率 html 檔案的目錄-->
<logging>
<log type="coverage-html" target="./tmp/cover" />
<log type="junit" target="./tmp/result.xml" />
</logging>
<!-- 錯誤日誌-->
<php>
<env name="LOCAL_ENV" value="test"/>
<env name="APP_ENV" value="test"/>
<ini name="error_log" value="/data/service/phpunit.log"/>
</php>
</phpunit>