PHPUnit Laravel Hash not available
Asked Answered
U

2

6

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]'),
  ]);
}
Upheld answered 30/12, 2016 at 12:14 Comment(2)
Is you test extending Laravel's TestCase?Gause
@RossWilson yep, extends TestCaseUpheld
R
11

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();
Registrant answered 30/12, 2016 at 12:16 Comment(5)
Class 'Hash' not found is returned. Note the import statement is present, use Illuminate\Support\Facades\Hash as Hash; doesn't work either.Upheld
that returns A facade root has not been set.Upheld
You forgot to call parent::setUp(); in setUp() method.Registrant
Yep that's what it was @AlexeyUpheld
by the way, what is the purpose of -> parent::setUp() thou it works, newbie at phpunit here. tia!Alvie
T
-1
  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);
    }

Tarnation answered 30/12, 2016 at 12:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.