我在 Yii2 中使用 Codeception 进行验收测试,但无法访问我的模型,因为命名空间不适用于这些测试。
我在我的测试/_bootstrap.php 中有这个
require(__DIR__ . '/../vendor/autoload.php');
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php');
$config = require(__DIR__ . '/../console/config/main.php');
//
$application = new yii\console\Application( $config );
## Added (@vitalik_74)
Yii::setAlias('@tests', dirname(__DIR__));
这在我的控制台/配置/主
<?php
$params = array_merge(
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
'log' => [
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
],
'params' => $params,
];
<?php
return [
'adminEmail' => 'admin@example.com',
'supportEmail' => 'support@example.com',
'user.passwordResetTokenExpire' => 3600,
];
这是想要的测试之一:
<?php namespace tests\acceptance;
use \AcceptanceTester;
use backend\models\User; ## I have tried writing it with a / at the beggining
class ListUserCest
{
public function _before(AcceptanceTester $I)
{
}
public function _after(AcceptanceTester $I)
{
}
public function init(AcceptanceTester $I)
{
$this->login($I);
if( User::find()->exists() )
$I->amGoingTo('List Users having at least one');
else
$I->amGoingTo('List Users having any');
}
...
运行测试时出现此错误:
PHP Fatal error: Class 'backend\models\User' not found in /var/www/project/tests/acceptance/ListUserCest.php on line 21 Error: Class 'backend\models\User' not found
请帮助我,我已经尝试了我所知道的一切
编辑
现在(在添加了vitalik_74 推荐的行之后)我可以在测试中使用例如\Yii 方法,但是没有Web 应用程序配置,只有控制台配置。
我的意思是,我仍然不能使用\backend\models\User 并且我也不能访问 Yii::$app->user 状态(例如检查用户是否已登录)。
User 模型只是一个普通的 ActiveRecord 模型,有他的 tableName、rules、attributeLabels 和一些像 getProfile() 这样的关系方法。
它在测试中起作用
<?php
namespace backend\models;
use common\helpers\MathHelper;
use backend\models\AntropometricData;
use Yii;
class User extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
...
最佳答案
将下一个代码放到 tests/_bootstrap.php 中:
require('vendor/autoload.php');
require('vendor/yiisoft/yii2/Yii.php');
$config = require('config/web.php');
(new yii\web\Application($config));
关于命名空间不适用于 Codeception (Yii2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29681347/