Codeception 簡介
Codeception 是一套很優秀的測試框架, 優秀的地方在於, 除了基本的 Unit Test 之外, 也設計了 Functional Test 與 Acceptance Test 的模組, 反正不用掙扎了, 就算你現在只寫 Unit Test, 早晚你還是要面對其他兩種測試, 不如現在趕快學起來吧 :D
One of the main advantages of Codeception is that you don’t have to decide on just one type of testing. You should have all three! And chances are, that you will (sooner or later) need all three.
- 官網 https://codeception.com/
- Quick start https://codeception.com/quickstart
特點
相對於 PHPUnit 來說, 測試更為彈性, 也相容於 Laravel、Yii Framework、Phalcon, 可以依據需求調整測試粒度, 測試粒度由粗到細, 可細分為
- Acceptance Test (粗):可以理解為完整的 E2E 測試,適合模擬非技術人員在網頁上的操作測試,會啟動一個測試用的 Web Server (PhpBrowser),測試時間較長。
- Functional Test (中):可以理解為針對 API specification 測試,不會受 javascript 設定影響,只對 Request、Response 相關欄位做驗證,不需要 Web Server。
- Unit Test (細):單元測試,針對 Class 與 Function 做的測試。
缺點就是學習門檻比較高一點點, 畢竟這可是一個能滿足你三種測試願望的測試框架, 但相對來說, 開發者也比較容易意識到用對的方法測試相應的情境, 像 Functional Test 就很適合寫來重構 Legency Code (Tears)。
基本介紹
建立 Suite
Suite 指的就是 Acceptance Test、Functional Test、Unit Test,但有時候要測的東西可能介於 Acceptance 與 Functional 之間, 像是 APIs Specification Test 所以我習慣會建立一個適用於我的測試情境的 Suite, 建立後會產生一份 your_suite.suite.yml, 方便我引入對應的 Modules。
codecept generate:suite your_suite
Actor 概念
我覺得 Actor (表演者) 這個概念超棒的, Codeception 的精神就是讓你寫一個劇本, 讓 Actor 照你的測試腳本去表演, 某個 Actor 可能扮演 Unit Tester, 或是某個 Actor 扮演 Functional Tester, 可以想像有某個 QA 照著你的腳本拿到某個 Module 開始在測試舞台上, 做著你告訴他的事。
your_suite.suite.yml 文件
這個文件, 就是定義 Actor 跟 Modules, 每個 module 都會提供一組 Action, 比如說: PhpBrowser 模組, 就提供了 Guzzle 套件, 可以進行 CURL actions。
建立 Suite 底下的測試案例
codecept generate:cest your_suite MyTest
這邊就是測試的重點了, 通常我會把測試範圍跟情境定義清楚, 盡可能地不要在一個測試, 驗證兩種情境, 舉例來說, 登入成功的測試, 就不要在登入成功的測試裡面再去驗證 Exception, 登入發生的 Exception 應該算另一個測試情境, 在測試時就可以順便整理 Functional 的情境了。
官方的範例像這樣, $I 就照著 loginSuccessfully 的腳本演出, 滿好理解的吧。
class SigninCest
{
public function loginSuccessfully(AcceptanceTester $I)
{
$I->amOnPage('/login');
$I->fillField('Username','davert');
$I->fillField('Password','qwerty');
$I->click('Login');
$I->see('Hello, davert');
}
}
build 指令
就如同 build 字面上的意思, 它會協助你產生所有測試 Actor 可用的 actions,比如說 REST module 透過 Build 產生的 actor 就擁有sendPost($url, $payload) 的 method,直覺好懂的去寫 Functional Test。
codecept build
簡單的範例
protected function call($url, $payload, $status = 200)
{
$this->I->haveHttpHeader('Content-Type', 'application/json');
$this->I->sendPOST($url, $payload);
$this->I->seeResponseCodeIs($status);
$this->I->seeResponseIsJson(); return json_decode($this->I->grabResponse(), true);
}public function _before(MyTester $I)
{
$this->I = $I;
}public function invokeMyApiIsOk(MyTester $I)
{
$url = self::PATH;
$payload = [
'key1' => 'value1',
'key2' => 'value2'
];$this->call($url, $payload);
}
介紹的有點隨便, 但真心覺得是一套不錯而且優美的測試框架, 獻給寫 PHP 的朋友們 :D