首頁 > php框架 > Laravel > 主體

介紹Laravel unit test : 模擬認證的用戶

藏色散人
發布: 2021-04-25 08:53:34
轉載
1550 人瀏覽過

#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('/');
    }
}
登入後複製
#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');
登入後複製
後續會繼續寫一些單元測試小細節的文章,歡迎關注: )

相關推薦:
最新的五個Laravel影片教學

以上是介紹Laravel unit test : 模擬認證的用戶的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:segmentfault.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!