yii如何寫單元測試

單元測試

單元測試位于tests/unit目錄中,應(yīng)該包含所有類型的單元和集成測試。

yii如何寫單元測試

每個測試用例都擴展了CodeceptionTestUnit類,這是用于單元測試的標(biāo)準(zhǔn)Codeception格式。在YII中開發(fā)完全隔離的單元測試非常困難,因此在每個測試用例之前都要啟動一個應(yīng)用程序。? ? ? ? ? ? ? ? ? (推薦學(xué)習(xí):yii教程

在tests/unit.suite.yml啟用了Yii2模塊的文件中配置測試:

modules: ????enabled: ??????-?Yii2: ????????????part:?[orm,?email]

該模塊為一個測試案例啟動Yii應(yīng)用程序,并提供其他幫助程序方法來簡化測試。它只有orm和email零件,以排除需要的只是功能性的測試方法。

通過訪問$this->tester測試用例中的類,可以使用Yii2模塊的方法。因此,如果啟用了orm和email部分,則可以調(diào)用屬于這些部分的方法:

<?php // insert records in database $this->tester-&gt;haveRecord('app/model/User',?['username'?=&gt;?'davert']); //?check?records?in?database $this-&gt;tester-&gt;seeRecord('app/model/User',?['username'?=&gt;?'davert']); //?test?email?was?sent $this-&gt;tester-&gt;seeEmailIsSent(); //?get?a?last?sent?emails $this-&gt;tester-&gt;grabLastSentEmail();

如果啟用fixtures零件,您還將獲得在測試中加載和使用夾具的方法:

<?php // load fixtures $this->tester-&gt;haveFixtures([ ????'user'?=&gt;?[ ????????'class'?=&gt;?UserFixture::className(), ????????//?fixture?data?located?in?tests/_data/user.php ????????'dataFile'?=&gt;?codecept_data_dir()?.?'user.php' ????] ]); //?get?first?user?from?fixtures $this-&gt;tester-&gt;grabFixture('user',?0);

如果Yii2啟用了模塊,則可以安全地Yii::$app在測試內(nèi)調(diào)用,因為在測試后將初始化并清理應(yīng)用程序。如果你想添加的輔助方法或自定義斷言為您的測試情況下,你不應(yīng)該延長CodeceptionTestUnit,但寫自己的獨立的輔助類。

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點贊11 分享