Laravel unit test : 模擬認(rèn)證的用戶
在 Laravel 編寫單元測試時(shí)經(jīng)常會遇到需要模擬認(rèn)證用戶的時(shí)候,比如新建文章、創(chuàng)建訂單等,那么在 Laravel unit test 中如何來實(shí)現(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('/'); } }
其實(shí)就是使用 Laravel Testing IlluminateFoundationTestingConcernsImpersonatesUsers
Trait 中的 actingAs
和 be
方法。
設(shè)置以后在后續(xù)的測試代碼中,我們可以通過 auth()->user()
等方法來獲取當(dāng)前認(rèn)證的用戶。
偽造認(rèn)證用戶
在官方的示例中有利用 factory 來創(chuàng)建一個(gè)真實(shí)的用戶,但是
相關(guān)推薦
- 2025年國內(nèi)免費(fèi)AI工具推薦:文章生成與圖像創(chuàng)作全攻略
- 從流量變現(xiàn)到信任變現(xiàn):個(gè)人站長的私域運(yùn)營方法論
- AI時(shí)代,個(gè)人站長如何用AI工具實(shí)現(xiàn)“一人公司”
- 個(gè)人站長消亡論?從“消失”到“重生”的三大破局路徑
- raksmart法蘭克福云服務(wù)器延遲高嗎?
- 自媒體人搭建直播服務(wù)器使用raksmart優(yōu)化技巧
- 華納云高防服務(wù)器3.6折起低至1188元/月,企業(yè)級真實(shí)防御20G`T級,自營機(jī)房一手服務(wù)器資源
- 服務(wù)器的系統(tǒng)和普通電腦系統(tǒng)一樣嗎?