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

时间:2016-05-26 13:06:10

标签: php unit-testing yii2 codeception

<?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 = 'alk@gmail.com';
        $this->assertEquals(true, $account->isEmailAvailable($email));

        // 2. New email check
        $email = 'arulvel@gmail.com';
        $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致命错误:在

中调用null上的成员函数getDb()

/无功/网络/ HTML /奖励/ shopsup的奖励 -

第133行

web / htdocs / vendor / yiisoft / yii2 / db / ActiveRecord.php

致命错误。测试未完成。 在null

上调用成员函数getDb()

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

enter image description here

是否需要进行任何配置?

1 个答案:

答案 0 :(得分:0)

来自Github

  

如果是单元测试,您有责任创建应用程序   实例

来自Yii Forum

  

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

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';