Laravel unit test : 模擬認證的用戶

在 Laravel 編寫單元測試時經常會遇到需要模擬認證用戶的時候,比如新建文章、創建訂單等,那麼在 Laravel unit test 中如何來實現呢?

官方解決方法

Laravel 的官方文檔中的測試章節中有提到:

Of course, one common use of the session is for maintaining state for the authenticated user. The actingAs helper method provides a simple way to authenticate a given user as the current user. For example, we may use a model factory to generate and authenticate a user:

<?php

use App\User;

class ExampleTest extends TestCase
{
    public function testApplication()
    {
        $user = factory(User::class)->create();

        $response = $this->actingAs($user)
                         ->withSession(['foo' => 'bar'])
                         ->get('/');
    }
}

其實就是使用 Laravel Testing Illuminate\Foundation\Testing\Concerns\ImpersonatesUsers Trait 中的 actingAsbe 方法。

設置以後在後續的測試代碼中,我們可以通過 auth()->user() 等方法來獲取當前認證的用戶。

僞造認證用戶

在官方的示例中有利用 factory 來創建一個真實的用戶,但是更多的時候,我們只想用一個僞造的用戶來作爲認證用戶即可,而不是通過 factory 來創建一個真實的用戶。

在 tests 目錄下新建一個 User calss:

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    protected $fillable = [
        'id', 'name', 'email', 'password',
    ];
}

必須在 $fillable 中添加 id attribute . 否則會拋出異常: Illuminate\Database\Eloquent\MassAssignmentException: id

接下來僞造一個用戶認證用戶:

$user = new User([
    'id' => 1,
    'name' => 'ibrand'
]);

 $this->be($user,'api');

後續會繼續寫一些單元測試小細節的文章,歡迎關注 : )

討論交流

聯繫我們

發佈了34 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章