PHPUnit Laravel Hash not available

2.1k views Asked by At

I have a Unit test in Laravel for testing an API call that looks like this, however I am getting the following runtime error when running it:

RuntimeException: A facade root has not been set.

I'm creating a user in the setup method, with the intent to delete it again in the tearDown() method, then run my auth test.

Firstly, is there a better way of doing what I want? For example Mocking a user without touching the database? And secondly, how do I set a 'facade root' or what does that error mean exactly? I've tried not bothering to hash that particular field for the purposes of creating a Dummy user, but the error then seems to move to the model, where (again) the Hash facade class is used.

Is there any additional steps to setup the environment so these facades can be used in testing?

Thanks in advance.

use Illuminate\Support\Facades\Hash;

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

  $this->json('POST', $this->endpoint,
        [ 'email' => '[email protected]',
          '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' => '[email protected]',
      'password' => 'password',
      'hashed_email' => Hash:make('[email protected]'),
  ]);
}
2

There are 2 answers

5
Alexey Mezenin On BEST ANSWER

Try to use this instead:

\Hash::make('[email protected]'),

It's a good idea to use bcrypt() global helper instead of Hash::make()

Also, add this to setUp() method:

parent::setUp();
0
Matthias Weiß On
  1. You could use the DatabaseMigrations or DatabaseTransactions trait that comes with Laravel so you don't have to delete the User manually.

  2. You could add a Mutator to your User class, which will automatically hash the password when a User is created.



    // https://laravel.com/docs/5.3/eloquent-mutators

    public function setPasswordAttribute($value) {
        $this->attributes['password'] = bcrypt($value);
    }