คู่มือตั้งค่า PHPUnit Testing Framework ใน PhpStorm IDE แบบ Step-by-Step
ข้อกำหนดเบื้องต้น
- PhpStorm (Professional Edition หรือ Community + Plugin)
- PHP Interpreter ตั้งค่าแล้ว (Settings > PHP > CLI Interpreter)
- Composer ติดตั้งแล้วใน Project
ขั้นตอนที่ 1: ติดตั้ง PHPUnit ผ่าน Composer
# ใน Root ของ Project
composer require --dev phpunit/phpunit ^10.0 # PHP 8.1+
# หรือ
composer require --dev phpunit/phpunit ^9.5 # PHP 7.3-8.0
# ตรวจสอบ
./vendor/bin/phpunit --version
ขั้นตอนที่ 2: กำหนดค่า PHPUnit ใน PhpStorm
- เปิด Settings/Preferences (Ctrl+Alt+S / Cmd+,)
- ไปที่ Languages & Frameworks > PHP > Test Frameworks
- คลิก + → PHPUnit by Composer Autoloader
- เลือก Path to script:
vendor/autoload.php - คลิก OK - PhpStorm จะ Detect Version อัตโนมัติ
ขั้นตอนที่ 3: สร้าง phpunit.xml.dist (Configuration)
tests/Unit
tests/Integration
src
src
ขั้นตอนที่ 4: สร้าง Test Class (Generate)
- คลิกขวาที่ Class ที่ต้องการ Test → Generate (Alt+Insert) → PHPUnit Test
- เลือก Methods ที่ต้องการ Generate Test
- เลือก Target Directory (
tests/Unit) - คลิก OK
service = new UserService();
}
public function testCreateUser(): void {
$user = $this->service->createUser(['name' => 'John', 'email' => 'john@example.com']);
$this->assertInstanceOf(User::class, $user);
$this->assertEquals('John', $user->getName());
$this->assertEquals('john@example.com', $user->getEmail());
}
}
ขั้นตอนที่ 5: รันและ Debug Test
- Run: คลิกขวา Test Class/Method → Run '...' (Ctrl+Shift+F10)
- Debug: คลิกขวา → Debug '...' (Ctrl+Shift+D)
- Run with Coverage: คลิกขวา → Run '...' with Coverage
Run Configuration (Advanced)
# .phpstorm/runConfigurations/PHPUnit.xml
phpunit.xml.dist
เคล็ดลับ PhpStorm
- Auto-generate Test: Cursor อยู่ที่ Method → Alt+Enter → Create Test
- Navigate to Test: Ctrl+Shift+T (Toggle Class ↔ Test)
- Run Single Test: Click Gutter Icon (▶) ข้าง Method Name
- Data Providers: PhpStorm รองรับ
@dataProviderแสดง Case แยกกัน - Coverage Gutters: หลัง Run with Coverage จะมีสีเขียว/แดง บรรทัดที่ Cover/Not Cover
Troubleshooting
| ปัญหา | แก้ไข |
|---|---|
| Class not found | Check bootstrap=vendor/autoload.php, composer dump-autoload |
| PHP Version Mismatch | Settings > PHP > CLI Interpreter → เลือก Version ถูกต้อง |
| Test ไม่ Run | Filename ต้องลงท้าย *Test.php, Class ลงท้าย Test, Method ขึ้นต้น test* |
| Database Error | ใช้ SQLite :memory: หรือ Transaction Rollback ใน setUp/tearDown |