使用Facade::shouldReceive()可精確控制門面方法的調(diào)用、參數(shù)和返回值,適用於需要細(xì)粒度模擬的場景;2. 對於Mail、Notification等常見門面,應(yīng)優(yōu)先使用Mail::fake()等內(nèi)置fake方法,更簡潔且不易出錯;3. 模擬鍊式調(diào)用時需完整描述調(diào)用鏈如Mail::to()->send();4. 可通過partial mock僅模擬特定方法而保留其他真實行為;5. 避免在setUp()中設(shè)置僅個別測試需要的mock,防止測試間污染;6. 使用Mail::preventStrayRequests()可防止意外的郵件發(fā)送。應(yīng)根據(jù)場景選擇mock或fake,優(yōu)先使用Laravel提供的fake輔助方法以提升可讀性和穩(wěn)定性。
Mocking facades in Laravel tests is a common practice to isolate your code and avoid side effects from external services like mail, queue, or cache. Laravel provides a clean and simple way to mock facades using the Facade::shouldReceive()
method, thanks to its integration with PHPUnit and Mockery.

Here's how to do it properly:
? Use shouldReceive()
on the Facade
Laravel facades are static proxies to underlying services, and they can be easily mocked using shouldReceive()
. This method returns a Mockery mock instance, allowing you to define expectations.

Example: Mocking the Mail
facade
use Illuminate\Support\Facades\Mail; use Tests\TestCase; class UserControllerTest extends TestCase { public function test_sending_welcome_email() { // Arrange: Mock the Mail facade Mail::shouldReceive('to->send') ->once() ->with(\App\Mail\WelcomeEmail::class); // Act: Call the method that sends email $response = $this->post('/register', [ 'name' => 'John Doe', 'email' => 'john@example.com', 'password' => 'secret', ]); // Assert $response->assertRedirect(); } }
? Note: Because
Mail::to()
returns a mailable object, we chain->to->send
to mock the actual call sequence.
? Reset or Partial Mocking
Sometimes you want to mock only certain methods of a facade and keep others real. Laravel allows partial mocks using shouldReceive()
while preserving other methods.
Example: Mock only put()
on Storage
facade
use Illuminate\Support\Facades\Storage; Storage::shouldReceive('put') ->with('avatars/1.jpg', 'file-content') ->andReturn(true); // Other methods like `get()`, `exists()` will still work normally
? Prevent All Facade Calls (Optional)
If you want to ensure no unexpected facade usage happens, you can prevent all real calls:
Mail::preventStrayRequests();
This will throw an exception if any mail is sent without being explicitly mocked.
Alternatively, use:
Mail::fake(); // Recommended for newer Laravel versions
? Tip : Laravel also provides
Fake
classes (eg,Mail::fake()
,Notification::fake()
) which are often easier and more readable than manual mocking.
? Mocking vs Faking
Approach | When to Use |
---|---|
Facade::shouldReceive() | When you need precise control over method calls, arguments, call count, or return values. |
Facade::fake() | Simpler, cleaner — use when built-in fake helpers are available (Mail, Notification, Queue, etc). |
Example using Mail::fake()
(preferred for mail):
use Illuminate\Support\Facades\Mail; Mail::fake(); // Perform action $this->post('/register', [...]); // Assert message was sent Mail::assertSent(WelcomeEmail::class);
Use fake()
when possible — it's simpler and less error-prone.
?? Common Pitfalls
- Forgetting chained methods : Facades like
Mail::to()->send()
involve intermediate objects. You must mock the full chain. - Over-mocking : Only mock what you need. Prefer
fake()
for standard facades. - Not resetting mocks : In some cases, especially in
setUp()
, mocks can leak between tests. Avoid setting global mocks unless necessary.
? Pro Tip: Use shouldReceive()
in setUp()
carefully
If you're setting up a mock in setUp()
, make sure it applies to all tests — otherwise, move it into individual test methods.
public function setUp(): void { parent::setUp(); // Only do this if ALL tests need it Cache::shouldReceive('get')->andReturn('cached-value'); }
In short:
Use Facade::shouldReceive()
when you need fine-grained control, but lean on Laravel's ::fake()
methods when available — they're simpler and less brittle.
Basically, mock facades only when necessary, and prefer Laravel's testing helpers when they exist.
以上是如何在Laravel測試中嘲笑外牆?的詳細(xì)內(nèi)容。更多資訊請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

toworkeffectivelywithpivottablesinlaravel,firstAccessPivotDatausingwithPivot()orwithTimestamps(),thenupdateentrieswithupdatee XistingPivot(),ManageraliationShipsviadeTach()andsync(),andusecustompivotModelSwhenNeed.1.UseWithPivot()toincludespecificcol

laravelProvidesLeanAndFlexibleWayTosendificationsViamultiplipliplipliplikeMail,SMS,In-Appalerts,and-Appalerts,andPushNotifications.youdefineNotificationChannelsinthelsinthevia()MethodofanotificationClass,andimpecificementpecificementpecificementpecificemmethodssliketomail()

Laravel性能優(yōu)化可通過四個核心方向提升應(yīng)用效率。 1.使用緩存機制減少重複查詢,通過Cache::remember()等方法存儲不常變化的數(shù)據(jù),降低數(shù)據(jù)庫訪問頻率;2.從模型到查詢語句進行數(shù)據(jù)庫優(yōu)化,避免N 1查詢、指定字段查詢、添加索引、分頁處理及讀寫分離,減少瓶頸;3.將耗時操作如郵件發(fā)送、文件導(dǎo)出放入隊列異步處理,利用Supervisor管理工作者並設(shè)置重試機制;4.合理使用中間件與服務(wù)提供者,避免複雜邏輯和不必要的初始化代碼,延遲加載服務(wù)以提升啟動效率。

在Laravel測試中管理數(shù)據(jù)庫狀態(tài)的方法包括使用RefreshDatabase、選擇性播種數(shù)據(jù)、謹(jǐn)慎使用事務(wù)和必要時手動清理。 1.使用RefreshDatabasetrait自動遷移數(shù)據(jù)庫結(jié)構(gòu),確保每次測試都基於乾淨(jìng)的數(shù)據(jù)庫;2.通過調(diào)用特定種子填充必要數(shù)據(jù),結(jié)合模型工廠生成動態(tài)數(shù)據(jù);3.使用DatabaseTransactionstrait回滾測試更改,但需注意其局限性;4.在無法自動清理時,手動截斷表或重新播種數(shù)據(jù)庫。這些方法根據(jù)測試類型和環(huán)境靈活選用,以保證測試的可靠性和效率。

LaravelSanctum適合簡單、輕量的API認(rèn)證,如SPA或移動應(yīng)用,而Passport適用於需要完整OAuth2功能的場景。 1.Sanctum提供基於令牌的認(rèn)證,適合第一方客戶端;2.Passport支持授權(quán)碼、客戶端憑證等複雜流程,適合第三方開發(fā)者接入;3.Sanctum安裝配置更簡單,維護成本低;4.Passport功能全面但配置複雜,適合需要精細(xì)權(quán)限控制的平臺。選擇時應(yīng)根據(jù)項目需求判斷是否需要OAuth2特性。

Laravel通過內(nèi)置支持簡化了數(shù)據(jù)庫事務(wù)處理。 1.使用DB::transaction()方法可自動提交或回滾操作,確保數(shù)據(jù)完整性;2.支持嵌套事務(wù)並通過保存點實現(xiàn),但通常建議使用單一事務(wù)包裝以避免複雜性;3.提供手動控制方法如beginTransaction()、commit()和rollBack(),適用於需要更靈活處理的場景;4.最佳實踐包括保持事務(wù)簡短、僅在必要時使用、測試失敗情況並記錄回滾信息。合理選擇事務(wù)管理方式有助於提高應(yīng)用可靠性和性能。

在Laravel中處理HTTP請求和響應(yīng)的核心在於掌握請求數(shù)據(jù)獲取、響應(yīng)返回和文件上傳。 1.接收請求數(shù)據(jù)可通過類型提示注入Request實例並使用input()或魔術(shù)方法獲取字段,結(jié)合validate()或表單請求類進行驗證;2.返迴響應(yīng)支持字符串、視圖、JSON、帶狀態(tài)碼和頭部的響應(yīng)及重定向操作;3.處理文件上傳時需使用file()方法並結(jié)合store()存儲文件,上傳前應(yīng)驗證文件類型和大小,存儲路徑可保存至數(shù)據(jù)庫。

在Laravel中生成命名路由的URL最常用方法是使用route()輔助函數(shù),它可根據(jù)路由名稱自動匹配路徑並處理參數(shù)綁定。 1.在控制器或視圖中傳入路由名稱和參數(shù),如route('user.profile',['id'=>1]);2.多參數(shù)時也只需傳數(shù)組,順序不影響匹配,如route('user.post.show',['id'=>1,'postId'=>10]);3.在Blade模板中可直接嵌入鏈接,如查看資料;4.可選參數(shù)未提供時不顯示,如route('user.post',
