【问题标题】:PHPUnit Laravel Hash not availablePHPUnit Laravel 哈希不可用
【发布时间】:2017-05-14 17:55:54
【问题描述】:

我在 Laravel 中有一个单元测试,用于测试如下所示的 API 调用,但是在运行它时出现以下运行时错误:

RuntimeException: A facade root has not been set.

我在 setup 方法中创建一个用户,目的是在 tearDown() 方法中再次删除它,然后运行我的身份验证测试。

首先,有没有更好的方法来做我想做的事?例如在不接触数据库的情况下模拟用户?其次,如何设置“立面根”或该错误究竟意味着什么?为了创建 Dummy 用户,我尝试不打扰该特定字段的哈希值,但错误似乎转移到模型,其中(再次)使用了 Hash 外观类。

是否有任何额外的步骤来设置环境,以便可以在测试中使用这些外观?

提前致谢。

use Illuminate\Support\Facades\Hash;

/*
* Make sure the structure of the API call is sound.
*/
public function testAuthenticateFailed()
{

  $this->json('POST', $this->endpoint,
        [ 'email' => 'test@test.com',
          'password' => 'password',
        ])
         ->seeJsonStructure([
             'token'
  ]);

}

//create a user if they don't already exist.
public function setup()
{
  $user = User::create([
      'company_id' => 9999,
      'name'=>'testUser',
      'email' => 'test@test.com',
      'password' => 'password',
      'hashed_email' => Hash:make('test@test.com'),
  ]);
}

【问题讨论】:

  • 你在测试扩展 Laravel 的 TestCase 吗?
  • @RossWilson 是的,扩展了 TestCase

标签: php laravel phpunit laravel-facade


【解决方案1】:

尝试改用这个:

\Hash::make('test@test.com'),

最好使用bcrypt() 全局助手而不是Hash::make()

另外,将此添加到setUp() 方法:

parent::setUp();

【讨论】:

  • 类 'Hash' not found 返回。注意 import 语句存在,使用 Illuminate\Support\Facades\Hash 作为 Hash;也不行。
  • 返回一个外观根尚未设置。
  • 您忘记在setUp() 方法中调用parent::setUp();。
  • 是的,这就是@Alexey
  • 顺便说一下,-> parent::setUp() 的作用是什么,phpunit 的新手。蒂亚!
【解决方案2】:
  1. 你可以使用 Laravel 自带的 DatabaseMigrations 或 DatabaseTransactions trait,这样你就不必手动删除用户了。

  2. 您可以在 User 类中添加一个 Mutator,它会在创建用户时自动散列密码。

// https://laravel.com/docs/5.3/eloquent-mutators public function setPasswordAttribute($value) { $this->attributes['password'] = bcrypt($value); }

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 2020-06-28
    • 1970-01-01
    • 2020-06-07
    • 2017-11-30
    • 1970-01-01
    • 2014-11-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多