0

我有一个密码修改器:

/**
 * 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'.

测试失败后,我尝试 dd() 密码属性,但这也失败了。我的第一个想法是这可能是一个批量分配问题(刚刚阅读过),但是密码在 $fillable 中(这很有意义,它会在那里),然后我注意到 User 类中的 $hidden 也是如此,但是之后在文档中阅读相关内容,并删除 $hidden 的密码索引,当您尝试访问密码属性时,它仍然会产生空值。

您将如何对这个 mutator 进行单元测试,或者我错过了什么?

4

1 回答 1

3

您只需将方法名称中的“get”更改为“set”。

以“get”开头的方法是访问器。这些不应该改变字段/属性值,而是返回一个“变异”值(你的没有返回任何东西,这就是你得到的原因null)。

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

http://laravel.com/docs/5.0/eloquent#accessors-and-mutators

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

您可以隐藏“密码”,因为这不会影响您的测试。

PS如果我没记错的话,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));
}
于 2015-06-23T03:20:36.933 回答