如何使用YII框架编写有效的单元测试案例?
- 内容介绍
- 文章标签
- 相关推荐
本文共计324个文字,预计阅读时间需要2分钟。
相关专题
在tests/unit.suite.yml启用了Yii2模块的文件中配置测试:
modules: enabled: - Yii2: part: [orm, email]
该模块为一个测试案例启动Yii应用程序,并提供其他帮助程序方法来简化测试。它只有orm和email零件,以排除需要的只是功能性的测试方法。
通过访问$this->tester测试用例中的类,可以使用Yii2模块的方法。因此,如果启用了orm和email部分,则可以调用属于这些部分的方法:
<?php // insert records in database $this->tester->haveRecord('app/model/User', ['username' => 'davert']); // check records in database $this->tester->seeRecord('app/model/User', ['username' => 'davert']); // test email was sent $this->tester->seeEmailIsSent(); // get a last sent emails $this->tester->grabLastSentEmail();
如果启用fixtures零件,您还将获得在测试中加载和使用夹具的方法:
<?php // load fixtures $this->tester->haveFixtures([ 'user' => [ 'class' => UserFixture::className(), // fixture data located in tests/_data/user.php 'dataFile' => codecept_data_dir() . 'user.php' ] ]); // get first user from fixtures $this->tester->grabFixture('user', 0);
如果Yii2启用了模块,则可以安全地Yii::$app在测试内调用,因为在测试后将初始化并清理应用程序。如果你想添加的辅助方法或自定义断言为您的测试情况下,你不应该延长Codeception\Test\Unit,但写自己的独立的辅助类。
本文共计324个文字,预计阅读时间需要2分钟。
相关专题
在tests/unit.suite.yml启用了Yii2模块的文件中配置测试:
modules: enabled: - Yii2: part: [orm, email]
该模块为一个测试案例启动Yii应用程序,并提供其他帮助程序方法来简化测试。它只有orm和email零件,以排除需要的只是功能性的测试方法。
通过访问$this->tester测试用例中的类,可以使用Yii2模块的方法。因此,如果启用了orm和email部分,则可以调用属于这些部分的方法:
<?php // insert records in database $this->tester->haveRecord('app/model/User', ['username' => 'davert']); // check records in database $this->tester->seeRecord('app/model/User', ['username' => 'davert']); // test email was sent $this->tester->seeEmailIsSent(); // get a last sent emails $this->tester->grabLastSentEmail();
如果启用fixtures零件,您还将获得在测试中加载和使用夹具的方法:
<?php // load fixtures $this->tester->haveFixtures([ 'user' => [ 'class' => UserFixture::className(), // fixture data located in tests/_data/user.php 'dataFile' => codecept_data_dir() . 'user.php' ] ]); // get first user from fixtures $this->tester->grabFixture('user', 0);
如果Yii2启用了模块,则可以安全地Yii::$app在测试内调用,因为在测试后将初始化并清理应用程序。如果你想添加的辅助方法或自定义断言为您的测试情况下,你不应该延长Codeception\Test\Unit,但写自己的独立的辅助类。

