Laravel 5.1无法在用户密码突变体上运行测试


Laravel 5.1 Unable to Run Test on User Password Mutator

我有一个密码转换器:

/**
 * Mutator for setting the encryption on the user password.
 *
 * @param $password
 */
public function getPasswordAttribute($password)
{
    $this->attributes[ 'password' ] = bcrypt($password);
}

我正在尝试测试:

/**
 * A basic check of password mutator.
 *
 * @return void
 */
public function testCheckPasswordEncryptionUserAttribute()
{
    $userFactory = factory('Project'User')->create([
        'password' => 'test'
    ]);
    $user = User::first();
    $this->assertEquals(bcrypt('test'), $user->password);
}

当测试运行时,我得到了这个错误:

1) UserTest::testCheckPasswordEncryptionUserAttribute
Failed asserting that null matches expected '$2y$10$iS278efxpv3Pi6rfu4/1eOoVkn4EYN1mFF98scSf2m2WUhrH2kVW6'.

测试失败后,我试图添加()password属性,但也失败了。我的第一个想法是,这可能是一个大规模分配问题(刚刚读到这篇文章),但密码在$fillable中(这是有道理的),然后我注意到$hidden也隐藏在User类中,但在文档中读到这一点,并删除$hidden的密码索引后,当你试图访问密码属性时,它仍然会产生null。

你将如何对这个变异株进行单元测试,或者我错过了什么?

只需将方法名称中的"get"更改为"set"即可。

以"get"开头的方法是访问器。它们不应该更改字段/属性值,而是返回一个"突变"值(您的值不返回任何值,这就是您获得null的原因)。

以"set"开头的方法旨在更改字段(mutator)的值,这似乎正是您所需要的。

http://laravel.com/docs/5.0/eloquent#accessors-和突变

/**
 * Mutator for setting the encryption on the user password.
 *
 * @param $password
 */
public function setPasswordAttribute($password)
{
    $this->attributes['password'] = bcrypt($password);
}

你可以隐藏"密码",因为这不会影响你的测试。

第页。S.如果我没有错的话,factory('...')->create()返回一个新创建的模型('Illuminate'Database'Eloquent'Model)的实例,所以你不必执行User::first():

/**
 * A basic check of password mutator.
 *
 * @return void
 */
public function testCheckPasswordEncryptionUserAttribute()
{
    $user = factory('Project'User')->create(['password' => 'test']);
    $this->assertTrue(Hash::check('test', $user->password));
}