2016-12-30 41 views
2

我有Laravel單元測試用於測試API調用看起來像這樣,但我正在運行時,以下運行時錯誤:PHPUnit的Laravel哈希不可

RuntimeException: A facade root has not been set. 

我創建一個用戶在setup方法中,意圖在tearDown()方法中再次刪除它,然後運行我的認證測試。

首先,有沒有更好的方式做我想要的?例如在不觸摸數據庫的情況下嘲笑用戶?其次,我如何設置「立面根」或者那個錯誤究竟意味着什麼?我嘗試過不打算爲了創建虛擬用戶而對該特定字段進行哈希處理,但是錯誤似乎轉移到了模型中,在這裏(再次)使用了Hash facade類。

是否有任何額外的步驟來設置環境,以便這些外牆可用於測試?

在此先感謝。

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]'), 
    ]); 
} 
+0

是你測試延長Laravel的TestCase? –

+0

@RossWilson yep,擴展TestCase – Paul

回答

6

嘗試改用此:

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

這是一個好主意,用bcrypt()全球幫手,而不是Hash::make()

此外,這增加setUp()方法:

parent::setUp(); 
+0

返回找不到類'Hash'。請注意導入語句存在,使用Illuminate \ Support \ Facades \ Hash作爲哈希;也不起作用。 – Paul

+0

返回尚未設置門面根目錄。 – Paul

+0

你忘記了在'setUp()'方法中調用'parent :: setUp();'。 –

-1
  1. 您可以使用Laravel附帶的DatabaseMigrationsDatabaseTransactions特徵,因此您不必手動刪除用戶。

  2. 您可以將一個Mutator添加到您的User類中,該類將在創建用戶時自動哈希密碼。

 


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

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