開發過程中常遇到:功能完成卻屢現 Bug、修復一處卻引發新錯誤、重構不敢動手。單元測試能有效解決這些痛點——它不僅能及早發現錯誤,更能讓程式碼更易維護、重構更有信心。只要測試通過,即證明修改未破壞既有功能。
pear channel-discover pear.phpunit.de pear channel-discover components.ez.no pear channel-discover pear.symfony-project.com pear install phpunit/PHPUnit
或參考官方手冊手動安裝:PHPUnit 安裝指南
<?php
class RemoteConnect {
public function connectToServer($serverName=null) {
if($serverName===null){
throw new Exception("That's not a server name!");
}
$fp = fsockopen($serverName, 80);
return ($fp) ? true : false;
}
public function returnSampleObject() {
return $this;
}
}
<?php
require_once('RemoteConnect.php');
class RemoteConnectTest extends PHPUnit_Framework_TestCase {
public function setUp(){ }
public function tearDown(){ }
public function testConnectionIsValid() {
$connObj = new RemoteConnect();
$serverName = 'www.google.com';
$this->assertTrue($connObj->connectToServer($serverName) !== false);
}
}
PHPUnit_Framework_TestCase,可使用 setUp()、tearDown()。被測類別名 + Test(如 RemoteConnectTest)。test 開頭,且必須為 public(如 testConnectionIsValid())。phpunit RemoteConnectTest.php
若顯示 OK (1 test, 1 assertion) 即代表通過。