Home >PHP Framework >YII >How to write unit tests in Yii
Unit tests
Unit tests are located in the tests/unit directory and should contain all types of unit and integration tests.
Each test case extends the Codeception\Test\Unit class, which is the standard Codeception format for unit testing. It is very difficult to develop fully isolated unit tests in Yii, so an application is started before each test case. (Recommended learning: yii tutorial )
Configure the test in the file with the Yii2 module enabled in tests/unit.suite.yml:
modules: enabled: - Yii2: part: [orm, email]
This module is A test case launches the Yii application and provides additional helper methods to simplify testing. It only has ORM and email parts, to rule out the need for only functional testing methods.
You can use the methods of the Yii2 module by accessing the class in the $this->tester test case. So if the orm and email parts are enabled, you can call methods belonging to these parts:
<?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();
If the fixtures part is enabled, you will also get methods to load and use fixtures in your tests:
<?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);
If Yii2 has the module enabled, it is safe to call Yii::$app within a test because the application will be initialized and cleaned up after the test. If you want to add helper methods or custom assertions for your test cases, you should not extend Codeception\Test\Unit, but write your own standalone helper class.
The above is the detailed content of How to write unit tests in Yii. For more information, please follow other related articles on the PHP Chinese website!