
- Symfony 教程
- Symfony - 主頁
- Symfony - 簡介
- Symfony - 安裝
- Symfony - 架構
- Symfony - 元件
- Symfony - 服務容器
- Symfony - 事件和事件偵聽器
- Symfony - 表示式
- Symfony - 捆綁包
- 建立簡單的 Web 應用程式
- Symfony - 控制器
- Symfony - 路由
- Symfony - 檢視引擎
- Symfony - Doctrine ORM
- Symfony - 表單
- Symfony - 驗證
- Symfony - 檔案上傳
- Symfony - Ajax 控制元件
- Cookie 和會話管理
- Symfony - 國際化
- Symfony - 日誌記錄
- Symfony - 電子郵件管理
- Symfony - 單元測試
- Symfony - 高階概念
- Symfony - REST Edition
- Symfony - CMF Edition
- 完整的操作範例
- Symfony 實用資源
- Symfony - 快速指南
- Symfony - 實用資源
- Symfony - 討論
Symfony - 單元測試
單元測試對於大型專案持續開發至關重要。單元測試會自動測試你應用程式的元件,並在你遇到問題時提醒你。單元測試可以手動完成,但經常是自動化的。
PHPUnit
Symfony 框架集成了 PHPUnit 單元測試框架。要為 Symfony 框架編寫一個單元測試,我們需要設定 PHPUnit。如果 PHPUnit 未安裝,則下載並安裝它。如果已正確安裝,你將看到以下響應。
phpunit PHPUnit 5.1.3 by Sebastian Bergmann and contributors
單元測試
單元測試是對單個 PHP 類的測試,該類也稱為單元。
在 AppBundle 的 Libs/ 目錄中建立一個 Student 類。該類位於 “src/AppBundle/Libs/Student.php”。
Student.php
namespace AppBundle\Libs; class Student { public function show($name) { return $name. “ , Student name is tested!”; } }
現在,在 “tests/AppBundle/Libs” 目錄中建立一個 StudentTest 檔案。
StudentTest.php
namespace Tests\AppBundle\Libs; use AppBundle\Libs\Student; class StudentTest extends \PHPUnit_Framework_TestCase { public function testShow() { $stud = new Student(); $assign = $stud->show(‘stud1’); $check = “stud1 , Student name is tested!”; $this->assertEquals($check, $assign); } }
執行測試
要執行目錄中的測試,請使用以下命令。
$ phpunit
執行以上命令之後,你將看到以下響應。
PHPUnit 5.1.3 by Sebastian Bergmann and contributors. Usage: phpunit [options] UnitTest [UnitTest.php] phpunit [options] <directory> Code Coverage Options: --coverage-clover <file> Generate code coverage report in Clover XML format. --coverage-crap4j <file> Generate code coverage report in Crap4J XML format. --coverage-html <dir> Generate code coverage report in HTML format.
現在,按以下方式執行 Libs 目錄中的測試。
$ phpunit tests/AppBundle/Libs
結果
Time: 26 ms, Memory: 4.00Mb OK (1 test, 1 assertion)
廣告