mercredi 1 juin 2016

Unit testing error on database insert yii2 framework

I am trying to test my application using codeception unit tests. The problem I encounter is that when trying to test a model which extends ActiveRecord class my test stops due to an error which says:

yii\base\ErrorException: Trying to get property of non-object
1  C:\xampp\htdocs\vendor\yiisoft\yii2\base\Component.php:541
2  C:\xampp\htdocs\vendor\yiisoft\yii2\db\BaseActiveRecord.php:916
3  C:\xampp\htdocs\vendor\yiisoft\yii2\db\ActiveRecord.php:468
4  C:\xampp\htdocs\vendor\yiisoft\yii2\db\ActiveRecord.php:427
5  C:\xampp\htdocs\vendor\yiisoft\yii2\db\BaseActiveRecord.php:598
6  C:\xampp\htdocs\models\User.php:299
7  C:\xampp\htdocs\models\SignupForm.php:68
8  C:\xampp\htdocs\tests\codeception\unit\models\SignupFormTest.php:168

I tried digging deeper into this and I found out that the record actually gets saved, but the test, however, crashes when executing BaseActiveRecord's afterSave method. It tries to trigger an afterSave event and crashes.

$this->assertTrue(is_null($this->signupForm->signup()), 'If attributes not set validation will fail; null should be returned');
    $attributeArray = [
        'email' => 'test4@email.com',
        'name' => 'Test',
        'surname' => 'User',
        'phone' => '860000000',
        'password' => 'password',
        'repeat_password' => 'password',
        'role' => 'Administrator'
    ];
    $this->signupForm->setAttributes($attributeArray);
    $this->assertInstanceOf(User::className(), $this->signupForm->signup(), 'If attributes set validation will not fail; User should be returned');

My signup method:

public function signup()
{
    if ($this->validate()) {
        return User::create($this->attributes);
    }
    return NULL;
}

My create method:

public static function create($attributes)
{
    /** @var User $user */
    $user = new static();
    $user->setAttributes($attributes);
    $user->setPassword($attributes['password']);
    $user->generateAuthKey();
    if ($user->save()) {
        $auth = Yii::$app->authManager;
        $user->role = $auth->getRole($user->role);
        $auth->assign($user->role, $user->id);
        return $user;
    } else {
        return NULL;
    }
}

It all ends on $user->save(). I suspect perhaps somewhere along the way the attributes array gets lost somehow. I have been trying to figure this out on my own for quite a while so any thoughts will be appreciated.

Thank you in advance.

Aucun commentaire:

Enregistrer un commentaire