phpunit-selenium 擴充,作為 Selenium ClientYii 在 PHPUnit 基礎上封裝測試基類,需同時依賴 PHPUnit 與 Selenium。
Selenium 主支援 Firefox/Chrome,macOS 請先安裝 Firefox。
Selenium Server 為 Java 開發,需安裝 JDK。
$ brew install selenium-server-standalone
注意:下載源在 Google APIs,需翻牆。
啟動指令:
$ selenium-server -p 4444
安裝 Composer:
$ brew update $ brew tap josegonzalez/homebrew-php $ brew tap homebrew/versions $ brew install php55-intl $ brew install josegonzalez/php/composer
專案根目錄建立 composer.json:
{
"require-dev": {
"phpunit/phpunit": "4.7.*",
"phpunit/php-invoker": "*",
"phpunit/dbunit": ">=1.2",
"phpunit/phpunit-selenium": ">=1.2",
"phpunit/phpunit-story": "*"
}
}
安裝依賴:
$ sudo composer install
產生 vendor/bin/phpunit 執行檔。
進入 protected/tests 目錄,確保 Selenium Server 運行中:
$ ../../vendor/bin/phpunit functional/SiteTest.php
Firefox 將自動啟動執行測試,輸出:
PHPUnit 4.7.7 by Sebastian Bergmann and contributors. Warning: Deprecated configuration setting "selenium" used . Time: 11.52 seconds, Memory: 6.50Mb OK (1 test, 1 assertion)
protected/tests/ ├── fixtures/ # 測試固定資料 ├── functional/ # 功能測試 ├── unit/ # 單元測試 ├── report/ # 覆蓋率報告 ├── bootstrap.php # 啟動腳本 ├── phpunit.xml # PHPUnit 設定 └── WebTestCase.php # 功能測試基類
$yiit = 'path/to/yii/framework/yiit.php'; $config = dirname(__FILE__).'/../config/test.php'; require_once($yiit); require_once(dirname(__FILE__).'/WebTestCase.php'); Yii::createWebApplication($config);
return CMap::mergeArray(
require(dirname(__FILE__).'/main.php'),
array(
'components' => array(
'fixture' => array(
'class' => 'system.test.CDbFixtureManager',
),
// 取消註解可使用獨立測試資料庫
// 'db' => array('connectionString' => 'DSN for test database'),
),
)
);
CDbFixtureManager 自動處理:
init.php, TableName.init.php)固定資料檔案範例 fixtures/Post.php:
return array(
'sample1' => array(
'title' => 'test post 1',
'content' => 'test post content 1',
'createTime' => 1230952187,
'authorId' => 1,
),
'sample2' => array(
'title' => 'test post 2',
'content' => 'test post content 2',
'createTime' => 1230952287,
'authorId' => 1,
),
);
# 執行單一測試 phpunit functional/PostTest.php # 執行功能測試目錄所有測試 phpunit --verbose functional # 執行單元測試並生成覆蓋率報告 (需 xdebug) phpunit --coverage-html ./report unit
完成上述配置,你將擁有專業級的 Yii 應用測試環境,支援持續整合與品質保證流程。