Laravel unit test : 模擬認證的用戶
在 Laravel 編寫單元測試時經(jīng)常會遇到需要模擬認證用戶的時候,比如新建文章、創(chuàng)建訂單等,那么在 Laravel unit test 中如何來實現(xiàn)呢?
官方解決方法
Laravel 的官方文檔中的測試章節(jié)中有提到:
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 AppUser; class ExampleTest extends TestCase { public function testApplication() { $user = factory(User::class)->create(); $response = $this->actingAs($user) ->withSession(['foo' => 'bar']) ->get('/'); } }
其實就是使用 Laravel Testing IlluminateFoundationTestingConcernsImpersonatesUsers
Trait 中的 actingAs
和 be
方法。
設置以后在后續(xù)的測試代碼中,我們可以通過 auth()->user()
等方法來獲取當前認證的用戶。
偽造認證用戶
在官方的示例中有利用 factory 來創(chuàng)建一個真實的用戶,但是