在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 中的<?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
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影片教學