3.0 版本大幅擴充功能,成為 PHP 測試生態基石。
解決:如何測試方法內部呼叫、隔離外部依賴(資料庫、API、檔案系統)。
<?php
class UserServiceTest extends PHPUnit_Framework_TestCase {
public function testRegisterCallsEmailService() {
// 建立 EmailService 偽對象
$mockEmail = $this->getMockBuilder('EmailService')
->setMethods(['sendWelcome'])
->getMock();
$mockEmail->expects($this->once())
->method('sendWelcome')
->with($this->equalTo('test@example.com'));
$service = new UserService($mockEmail);
$service->register('test@example.com');
}
}
getMockBuilder() 流暢介面建立偽對象expects() 設定呼叫次數預期with() 斷言參數PHPUnit 內建 PHPUnit_Extensions_SeleniumTestCase,支援:
<?php
class WebTest extends PHPUnit_Extensions_SeleniumTestCase {
protected function setUp() {
$this->setBrowser('*firefox');
$this->setBrowserUrl('https://localhost/app/');
}
public function testLogin() {
$this->open('/login');
$this->type('name=username', 'admin');
$this->type('name=password', 'secret');
$this->click('css=button[type=submit]');
$this->waitForPageToLoad(10000);
$this->assertTextPresent('歡迎回來');
}
}
需啟動 Selenium Server:java -jar selenium-server-standalone.jar
量化測試完整性,發現未測試代碼。
# 產生 HTML 報告 phpunit --coverage-html ./report ./tests
# PEAR 安裝 pear channel-discover pear.phpunit.de pear channel-discover components.ez.no pear channel-discover pear.symfony-project.com pear install phpunit/PHPUnit # 從 2.x 升級 # 類別前綴從 PHPUnit2_ 改為 PHPUnit_ # 建議全面遷移至新命名空間
Sebastian Bergmann,PHPUnit 創始人,eZ Systems 架構師,長期貢獻 PHP 核心與開源生態。
#[Test])facebook/webdriver + WebDriver)composer require --dev phpunit/phpunit