Laravel unit test : 模擬認(rèn)證的用戶(hù)
在 Laravel 編寫(xiě)單元測(cè)試時(shí)經(jīng)常會(huì)遇到需要模擬認(rèn)證用戶(hù)的時(shí)候,比如新建文章、創(chuàng)建訂單等,那么在 Laravel unit test 中如何來(lái)實(shí)現(xiàn)呢?
官方解決方法
Laravel 的官方文檔中的測(cè)試章節(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ù)的測(cè)試代碼中,我們可以通過(guò) auth()->user()
等方法來(lái)獲取當(dāng)前認(rèn)證的用戶(hù)。
偽造認(rèn)證用戶(hù)
在官方的示例中有利用 factory 來(lái)創(chuàng)建一個(gè)真實(shí)的用戶(hù),但是
idea社區(qū)版和商業(yè)版的區(qū)別是什么 下一篇
外媒拿到 LG UltraFine 32EP950 OLED 顯示器,預(yù)計(jì)很快上市
相關(guān)推薦
- raksmart香港裸機(jī)云站群服務(wù)器對(duì)網(wǎng)站優(yōu)化的幫助
- raksmart香港裸機(jī)云站群服務(wù)器對(duì)網(wǎng)站優(yōu)化的幫助
- 站長(zhǎng)這樣做,外鏈多到根本發(fā)不完
- raksmart海外大帶寬服務(wù)器連接失敗怎么處理
- AI工具導(dǎo)航網(wǎng)站,未來(lái)的發(fā)展前景怎么樣?
- 在RAKsmart服務(wù)器上怎么管理數(shù)據(jù)科學(xué)工作流
- raksmart日本云服務(wù)器產(chǎn)品優(yōu)勢(shì)
- 算力服務(wù)器多少錢(qián)一臺(tái)??jī)r(jià)格因素與選購(gòu)指南