1. 安裝PHPUnit
在Ubuntu終端中,通過Composer全局安裝PHPUnit(推薦方式,便于項目級管理):
composer global require phpunit/phpunit
安裝完成后,將Composer的全局bin目錄添加到系統PATH中(如使用bash,編輯~/.bashrc
或~/.zshrc
文件,添加export PATH="$PATH:$HOME/.composer/vendor/bin"
,然后運行source ~/.bashrc
或source ~/.zshrc
使更改生效)。也可通過Ubuntu軟件倉庫安裝(sudo apt-get install phpunit/phpunit
),但全局安裝更靈活。
2. 配置PhpStorm使用PHPUnit
打開PhpStorm,進入File > Settings
(或PhpStorm > Preferences
,macOS用戶),導航至Tools > PHP > PHPUnit
:
/usr/bin/phpunit
或~/.composer/vendor/bin/phpunit
);若未檢測到,可手動指定路徑。Use configuration file
,指定項目根目錄下的phpunit.xml
配置文件路徑(后續步驟會創建)。OK
保存配置。3. 創建測試目錄與測試用例
在項目根目錄下創建tests
目錄(用于存放所有測試文件,符合PHPUnit約定)。新建測試類文件(如ExampleTest.php
),內容需繼承PHPUnit\Framework\TestCase
,且測試方法以test
開頭:
<?php
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testExample()
{
$this->assertTrue(true); // 斷言示例:驗證true等于true
}
public function testAddition()
{
$this->assertEquals(4, 2 + 2); // 斷言示例:驗證2+2等于4
}
}
測試類命名需遵循類名Test.php
規則(如UserModelTest.php
對應UserModel
類)。
4. 編寫phpunit.xml配置文件
在項目根目錄下創建phpunit.xml
文件,定義測試套件、白名單等配置(示例):
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php" colors="true">
<testsuites>
<testsuite name="Default Test Suite">
<directory suffix="Test.php">./tests</directory> <!-- 測試文件目錄及后綴 -->
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src</directory> <!-- 被測試代碼目錄(白名單) -->
</directory>
</filter>
</phpunit>
bootstrap
:指定項目自動加載文件(如Composer生成的vendor/autoload.php
),確保測試時能加載項目類。testsuites
:定義測試套件,指定測試文件所在目錄及命名規則(如suffix="Test.php"
表示以Test.php
結尾的文件)。filter
:設置被測試代碼的白名單(如src
目錄下的.php
文件),用于生成測試覆蓋率報告。5. 運行單元測試
PhpStorm提供多種運行測試的方式:
Run 'testMethodName()'
(如Run 'testAddition()'
)。ExampleTest.php
),選擇Run 'ExampleTest'
。tests
目錄,選擇Run 'All Tests'
;或在PhpStorm頂部工具欄點擊綠色三角形按鈕,從下拉列表中選擇PHPUnit配置。Run
工具窗口中,包含通過/失敗的測試數量、執行時間及錯誤詳情(如斷言失敗的具體信息)。6. 調試單元測試
若測試失敗或需要排查問題,可使用PhpStorm的調試功能:
Debug 'testMethodName()'
(如Debug 'testAddition()'
)。注意事項
File > Settings > PHP
,選擇正確的解釋器)。vendor/autoload.php
文件存在(運行composer install
生成)。phpunit.xml
中配置覆蓋率輸出(如<logging><coverage>
),通過Run
工具窗口查看代碼覆蓋率報告。