1. 準備測試環境
在Ubuntu系統中,確保已安裝PHP、Composer及PHPUnit(測試核心工具)。PHPUnit需作為開發依賴安裝,通過Composer添加:
composer require --dev phpunit/phpunit
安裝完成后,PHPUnit的可執行文件會位于項目根目錄的vendor/bin/
下(如vendor/bin/phpunit
)。
2. 配置PHPUnit
創建phpunit.xml
配置文件(項目根目錄),定義測試套件的路徑及自動加載規則。示例如下:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.5/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true">
<testsuites>
<testsuite name="Project Test Suite">
<directory>./tests</directory> <!-- 測試文件所在目錄 -->
</testsuite>
</testsuites>
</phpunit>
此配置會加載項目自動加載文件(vendor/autoload.php
),并指定tests/
目錄為測試文件目錄。
3. 編寫測試用例
在tests/
目錄下創建測試文件(如StringUtilsTest.php
),命名需遵循<ClassName>Test.php
規范。示例測試類(測試字符串工具類):
namespace VendorName\PackageName\Tests; // 替換為你的包命名空間
use PHPUnit\Framework\TestCase;
use VendorName\PackageName\StringUtils; // 替換為你的類路徑
class StringUtilsTest extends TestCase {
public function testCapitalize(): void {
$this->assertEquals('Hello World', StringUtils::capitalize('hello world'));
$this->assertEquals('Foo Bar', StringUtils::capitalize('foo bar'));
}
public function testSlugify(): void {
$this->assertEquals('hello-world', StringUtils::slugify('Hello World!'));
$this->assertEquals('foo-bar', StringUtils::slugify('Foo Bar@'));
}
}
測試方法需以test_
開頭(PHPUnit 9+支持void
返回類型),使用$this->assertEquals()
等斷言驗證結果。
4. 運行測試
通過Composer運行PHPUnit測試,命令如下:
vendor/bin/phpunit
若在composer.json
中配置了測試腳本(如"test": "phpunit"
),可直接使用:
composer test
運行后,PHPUnit會自動執行tests/
目錄下的所有測試用例,并輸出結果(如通過/失敗數量、錯誤詳情)。
5. 集成測試到開發流程(可選)
為確保每次代碼變更后自動運行測試,可將測試腳本添加到composer.json
的scripts
部分:
{
"scripts": {
"post-update-cmd": [
"phpunit" // 更新依賴后自動運行測試
],
"test": "phpunit" // 自定義測試命令
}
}
配置后,執行composer update
時會自動觸發測試,或通過composer test
手動運行。
注意事項
tests/
目錄(或phpunit.xml
中指定的目錄);composer.json
中的autoload
配置正確(如psr-4
自動加載),避免測試時類無法加載;launch.json
實現測試調試。