yii2 单元测试在 null 上调用成员函数 getDb() 时出错

问题描述 投票:0回答:2
<?php

namespace tests\codeception\engine;

use engine\components\BaseException;

use engine\components\BaseService;

use engine\modules\account\models\AccUser;

use engine\modules\account\models\AccUserActivity;

use engine\modules\account\services\AccountService;

use yii\db\Connection;



class AccountServiceTest extends \Codeception\TestCase\Test

{

    protected $tester;

    protected function _before()
    {
    }

    protected function _after()
    {
    }

    public function getDb()
    {
        $connection=Yii::$app->getDb();
    }

    public function testIsEmailAvailable()
    {
        $account = AccountService::model();


        // 1. Existing email check
        $email = '[email protected]';
        $this->assertEquals(true, $account->isEmailAvailable($email));

        // 2. New email check
        $email = '[email protected]';
        $this->assertEquals(false, $account->isEmailAvailable($email));

        // 3. Not an email check only character
        $email = 'arulvel';
        $this->assertEquals(false, $account->isEmailAvailable($email));

        // 4. Not an email check only numbers
        $email = '549876315';
        $this->assertEquals(false, $account->isEmailAvailable($email));

        // 5. Empty check
        $email = '';
        $this->assertEquals(false, $account->isEmailAvailable($email));

        return true;
    }

}

在运行测试时显示这样的错误

尝试测试电子邮件是否可用(AccountServiceTest::testIsEmailAvailable)...

PHP 致命错误:调用成员函数 getDb() on null in

/var/www/html/rewards/shopsup-rewards-

web/htdocs/vendor/yiisoft/yii2/db/ActiveRecord.php 第 133 行

致命错误。测试未完成。 在 null 上调用成员函数 getDb()

在第 133 行访问 ActiveRecord.php 时就像

enter image description here

有什么配置需要做吗??

php unit-testing yii2 codeception
2个回答
0
投票

来自Github

在单元测试的情况下,您有责任创建应用程序 实例。

来自Yii论坛

你可以设置数据库组件吗?

https://github.com/yiisoft/yii2-codeception/blob/master/TestCase.php#L36

class TestCase extends Test
{
    use FixtureTrait;
    /**
     * @var array|string the application configuration that will be used for creating an application instance for each test.
     * You can use a string to represent the file path or path alias of a configuration file.
     * The application configuration array may contain an optional `class` element which specifies the class
     * name of the application instance to be created. By default, a [[\yii\web\Application]] instance will be created.
     */
    public $appConfig = '@tests/codeception/config/unit.php';

0
投票

如果你使用 Yii2 高级模板。

编辑您的 unit.suite.yml 并将“orm”添加到零件数组中。

例如

suite_namespace: backend\tests\unit
actor: UnitTester
modules:
    enabled:
        - Yii2:
            part: [orm, email, fixtures]
        - Asserts
© www.soinside.com 2019 - 2024. All rights reserved.