在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:##Trait 中的#Illuminate\Foundation\Testing\Concerns\ImpersonatesUsers<?php use App\User; class ExampleTest extends TestCase { public function testApplication() { $user = factory(User::class)->create(); $response = $this->actingAs($user) ->withSession(['foo' => 'bar']) ->get('/'); } }登入後複製
actingAs 和
be 方法。
設定以後在後續的測試程式碼中,我們可以透過
auth()->user()
偽造認證用戶
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影片教學