7

Yii2 で Codeception を使用して受け入れテストを行っていますが、名前空間がこれらのテストで機能していないため、モデルにアクセスする方法がありません。

私はこれをtests/_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,
 ];

そして、これは志望者テストの1つです:

 <?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 致命的なエラー: 21 行目の /var/www/project/tests/acceptance/ListUserCest.php にクラス 'backend\models\User' が見つかりません エラー: クラス 'backend\models\User' が見つかりません

助けてください、知っていることはすべて試しました

編集

これで (vitalik_74 が推奨する行を追加した後)、たとえば \Yii メソッドをテストに使用できますが、Web アプリケーションの構成はなく、コンソールの構成のみを使用できます。つまり、まだ \backend\models\User を使用できず、Yii::$app->user ステータス (たとえば、ユーザーがログに記録されているかどうかを確認するため) にもアクセスできません。

User モデルは、tableName、rules、attributeLabels、および getProfile() などのいくつかのリレーショナル メソッドを備えた単なる一般的な ActiveRecord モデルです。それはテストからうまくいきます

<?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';
    }
...
4

1 に答える 1

2

次のコードを tests/_bootstrap.php に追加します。

require('vendor/autoload.php');
require('vendor/yiisoft/yii2/Yii.php');
$config = require('config/web.php');
(new yii\web\Application($config));
于 2016-04-29T09:27:39.470 に答える