最近研究了一下 PHP 的單元測試套件 PHPUnit,以下是簡單的筆記
測試環境
Xampp V5.6.3
安裝 PHPUnit
裝完 Xampp 才發現,原來 PHPUnit 已經內建在裡面了
命令位置在 C:\xampp\php\phpunit
可以輸入
C:\xampp\php> phpunit
會顯示該命令的說明
簡單的範例
假設以下檔案為 addTest.php
<?php // 一般來說這裡是 include 要測試的 Class // 不過這裡簡單寫死一個 function 來測試 function add($a, $b) {return $a + $b; } // 測試案例的 class class addTest extends PHPUnit_Framework_TestCase { public function test_add() { $this->assertEquals(2, add(1, 1)); } }
使用 Command Line 執行 PHPUnit
C:\xampp\php> phpunit D:\www\addTest.php PHPUnit 3.7.21 by Sebastian Bergmann. . Time: 0 seconds, Memory: 2.00Mb OK (1 test, 1 assertion)
以上結果表示有 1 個測試,1 個斷言,而且全部都通過了
如果有失敗的測試的話結果大概會像底下這樣
C:\xampp\php> phpunit D:\www\addTest.php PHPUnit 3.7.21 by Sebastian Bergmann.
F
Time: 0 seconds, Memory: 2.00Mb
There was 1 failure:
1) addTest::test_add
Failed asserting that 2 matches expected 3.
D:\www\addTest.php:12
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
代表有一個測試,兩個斷言,而其中一個的結果不符預期
使用 phpunit.xml 來進行專案的單元測試
一般的專案在進行似乎比較習慣用 phpunit.xml 來指定 phpunit 的相關設定(在 Github 上常看到)
phpunit.xml 的簡易範例
<?xml version="1.0" encoding="UTF-8"?> <phpunit> <testsuites> <testsuite name="PHPUnit"> <directory suffix="Test.php">tests</directory> </testsuite> </testsuites> </phpunit>
執行測試時要下
C:\xampp\php> phpunit -c {phpunit.xml 的路徑}
搭配 xdebug 產生涵蓋率報表
1. 必須先打開 xdebug 功能(以下指的是 xampp 環境)
* 打開 php.ini
* 找到最下面的 [XDebug]
* 將 ;zend_extension = "D:\xampp\php\ext\php_xdebug.dll" 的 ";" 拿掉
* 重開 apache
2. 執行 phpunit 指令
* C:\xampp\php> phpunit --coverage-html ./phpunit-report -c {phpunit.xml 的路徑}
3. 打開報表
* 請到剛才指令指定的目錄(如 ./phpunit-report) 打開 index.html
-----------------------------------------------------------------------------------------------------------------------------------
看看這 PHPUnit 產生出來的精美報表吧,感覺超開心的!
涵蓋率總表
單一檔案的涵蓋率
涵蓋範圍顯示
參考文件
http://twpug.net/docs/symblog/docs/testing-unit-and-functional-phpunit.html
https://phpunit.de/manual/current/zh_cn/code-coverage-analysis.html