PHPUnit + Selenium = Code Coverage Report
โดยปกติ PHPUnit ซึ่งใช้ทำ Unit test นั้น จะไม่สามารถทำการทดสอบผ่านเว็บบราวเซอร์ตรงๆได้ ดังนั้น ถ้าหากใช้รูปแบบการพัฒนาโปรแกรมแบบ MVC อาจจะทำการทดสอบได้เฉพาะ Model เท่านั้น หากจะทดสอบ View / Control ต้องใช้เครื่องมือคือ Selenium ในการทำการทดสอบผ่านหน้าเว็บบราวเซอร์
ดังนั้น ถ้าเราต้องการสร้าง Code Coverage Report ขึ้นมา จะต้องทำผ่าน Selenium Interface ด้วย. ผมได้เขียน Guideline ในการสร้าง Code Coverage Report กับ Yii Framework ไว้ที่ Yii Framework Forum ครับ รายละเอียดสามารถตามอ่านได้ตามลิงค์
เครื่องมือที่ผมใช้พัฒนา PHP ประกอบด้วย
- Apache 2
- Windows 7
- Netbeans 6.9.1 พร้อมกับ Selenium Plugin
- PHP 5.3 กับ XDebug module
- PEAR/PHPUnit
จริงๆ แล้วใน Netbeans website มี Tutorial อยู่เช่นกัน แต่ว่า ในส่วนนี้ ผมจะแนะนำสำหรับคนที่ทำเวอร์ชวลโฮส ที่มีเว็บไซต์หลายๆเว็บไซต์ภายในเครื่อง. แนะนำให้ทำเฉพาะเครื่องสำหรับ Development เท่านั้น สำหรับ Production server จะทำให้ช้าลงมาก ไม่แนะนำ
ก่อนอื่น ทำการแก้ไขไฟล์ ดังรายละเอียดด้านล่างนี้
File: %PEAR_Directory%/PHPUnit/Extensions/SeleniumTestCase/prepend.php
// $GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = FALSE; $GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = $_SERVER["DOCUMENT_ROOT"] ;
File: %PEAR_Directory%/PHPUnit/Extensions/SeleniumTestCase/phpunit_coverage.php
//$GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = getcwd(); $GLOBALS['PHPUNIT_COVERAGE_DATA_DIRECTORY'] = $_SERVER["DOCUMENT_ROOT"] ;
File: php.ini (ไฟล์ Configuration ของ PHP)
; Automatically add files before PHP document. auto_prepend_file = "D:\Service\var\scripts\PHPUnit\Extensions\SeleniumTestCase\prepend.php" ; Automatically add files after PHP document. auto_append_file = "D:\Service\var\scripts\PHPUnit\Extensions\SeleniumTestCase\append.php"
File: httpd.conf (ไฟล์ Configuration ของ Apache2)
<Directory "D:/Service/var/scripts"> Options FollowSymLinks Indexes Allow from all Order allow,deny AllowOverride All </Directory>
ขั้นตอนต่อไป เป็นขั้นตอนสำหรับทำให้ไดเรกทอรี่ดังกล่าว สามารถใช้ได้ในเว็บไซต์ใดๆ ที่อยู่ในเครื่อง
File: httpd.conf (ไฟล์ Configuration ของ Apache2)
# LoadModule alias_module modules/mod_alias.so LoadModule alias_module modules/mod_alias.so<IfModule alias_module> # ScriptAlias /cgi-bin/ "E:/Service/Process/Apache2.2/cgi-bin/" Alias /selenium-phpunit/ "D:/Service/var/scripts/PHPUnit/Extensions/SeleniumTestCase/" </IfModule>
ต่อมาขั้นตอนสำคัญ อย่าลืม Restart Apache 2 service
ต่อจากนี้เป็นขั้นตอนเพิ่มเติมสำหรับ Yii Framework
File: %YiiFramework%/protected/test/WebTest.php
// Add this to class protected $coverageScriptUrl = 'http://your.localhost./selenium-phpunit/phpunit_coverage.php';
จากนั้นอย่าลืมตรวจสอบไฟล์ phpunit.xml ให้ทำการสร้าง Code Coverage report เมื่อมีการทำการทดสอบ
File: %YiiFramework%/protected/test/phpunit.xml
<logging> <log type="coverage-html" target="%YiiFramework%\protected\tests\coverage" charset="UTF-8" yui="true" highlight="true" lowUpperBound="35" highLowerBound="70" /> </logging>
เสร็จครับ หมดแล้ว หลังจากนั้น เริ่มใช้งานได้เลย