使用composer方式安裝yii2-app-basic (https://github.com/yiisoft/yii2-app-basic/blob/master/README.md) 裝好後既可以使用
建一個Model文件EntryForm.php在models目錄下
<?php namespace app\models; use Yii; use yii\base\Model; class EntryForm extends Model { public $name; public $email; public function rules() { return [ [['name', 'email'], 'required'], ['email', 'email'], ]; } }
建一個EntryFormTest.php放在tests/unit/models目錄下
<?php namespace tests\models; use app\models\EntryForm; class EntryFormTest extends \Codeception\Test\Unit { public function testValidInput() { $model = new EntryForm(); $model->name = 'Harry Qin'; $model->email = '[email protected]'; expect_that($model->validate()); return $model; } public function testInvalidInput() { $model = new EntryForm(); $model->name = 'Harry Qin'; $model->email = 'xxyy'; expect_not($model->validate()); $model = new EntryForm(); $model->name = ''; $model->email = '[email protected]'; expect_not($model->validate()); } /** * 下面一行表示這裡輸入的參數值來自testValidInput的輸出 * @depends testValidInput */ public function testModelProperty($model) { expect($model->name)->equals('Harry Qin'); } }
項目根目錄下運行
composer exec codecept run unit
輸出
。。。。。。
✔ EntryFormTest: Valid input (0.00s)
✔ EntryFormTest: Invalid input (0.00s)
✔ EntryFormTest: Model property (0.00s)
這裡全部成功了,如果測試失敗,會顯示具體失敗信息。
這裡主要是3個方法
expect_that: 假設為true
expect_not: 假設為false
expect: 假設目標對象,後面可以接verify方法,具體方法列表在vendor/codeception/verify/src/Codeception/Verify.php文件中