# Laravel 測試之:測試模擬器
- [介紹](#introduction)
- [任務模擬](#bus-fake)
- [事件模擬](#event-fake)
- [郵件模擬](#mail-fake)
- [通知模擬](#notification-fake)
- [隊列模擬](#queue-fake)
- [Storage 模擬](#storage-fake)
- [Facades 模擬](#mocking-facades)
<a name="introduction"></a>
## 介紹
測試 Laravel 應用時,有時候你可能想要「模擬」實現應用的部分功能的行為,從而避免該部分在測試過程中真正執行。例如,控制器執行過程中會觸發一個事件( Events ),你想要模擬這個事件的監聽器,從而避免該事件在測試這個控制器時真正執行。如上可以讓你僅測試控制器的 HTTP 響應情況,而不用去擔心觸發事件。當然,你可以在單獨的測試中測試該事件的邏輯。
Laravel 針對事件、任務和 facades 的模擬提供了開箱即用的輔助函數。這些輔助函數基于 Mockery 封裝而成,使用非常簡單,無需你手動調用復雜的 Mockery 函數。當然,你也可以使用 [Mockery](http://docs.mockery.io/en/latest/) 或者 PHPUnit 創建自己的模擬器。
<a name="bus-fake"></a>
## 任務模擬
你可以使用 `Bus` facade 的 `fake` 方法來模擬任務執行,測試的時候任務不會被真實執行。使用 fakes 的時候,斷言一般出現在測試代碼的后面:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Jobs\ShipOrder;
use Illuminate\Support\Facades\Bus;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
public function testOrderShipping()
{
Bus::fake();
// 處理訂單發貨...
Bus::assertDispatched(ShipOrder::class, function ($job) use ($order) {
return $job->order->id === $order->id;
});
// 斷言任務并沒有被執行...
Bus::assertNotDispatched(AnotherJob::class);
}
}
<a name="event-fake"></a>
## 事件模擬
你可以使用 `Event` facade 的 `fake` 方法來模擬事件監聽,測試的時候不會觸發事件監聽器運行。然后你就可以斷言事件運行了,甚至可以檢查它們收到的數據。使用 fakes 的時候,斷言一般出現在測試代碼的后面:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Events\OrderShipped;
use App\Events\OrderFailedToShip;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
/**
* 測試訂單發貨.
*/
public function testOrderShipping()
{
Event::fake();
// 處理訂單發貨...
Event::assertDispatched(OrderShipped::class, function ($e) use ($order) {
return $e->order->id === $order->id;
});
Event::assertNotDispatched(OrderFailedToShip::class);
}
}
<a name="mail-fake"></a>
## 郵件模擬
你可以使用 `Mail` facade 的 `fake` 方法來模擬郵件發送,測試時不會真的發送郵件。然后你可以斷言 [mailables](/docs/{{version}}/mail) 發送給了用戶,甚至可以檢查他們收到的數據. 使用 fakes 時,斷言一般在測試代碼的后面:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
public function testOrderShipping()
{
Mail::fake();
// 處理訂單發貨...
Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
return $mail->order->id === $order->id;
});
// 斷言一封郵件已經發送給了指定用戶...
Mail::assertSent(OrderShipped::class, function ($mail) use ($user) {
return $mail->hasTo($user->email) &&
$mail->hasCc('...') &&
$mail->hasBcc('...');
});
// 斷言 mailable 發送了2次...
Mail::assertSent(OrderShipped::class, 2);
// 斷言 mailable 沒有發送...
Mail::assertNotSent(AnotherMailable::class);
}
}
如果你是用后臺任務隊執行 mailables 的發送,你應該用 `assertQueued` 方法來代替 `assertSent`:
Mail::assertQueued(...);
Mail::assertNotQueued(...);
<a name="notification-fake"></a>
## 通知模擬
你可以使用 `Notification` facade 的 `fake` 方法來模擬通知發送,測試的時候并不會真的發送通知。然后你可以斷言 [通知](/docs/{{version}}/notifications) 已經發送給你的用戶,甚至可以檢查他們收到的數據。使用 fakes 時, 斷言一般出現在測試代碼的后面.
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
public function testOrderShipping()
{
Notification::fake();
// 處理訂單發貨...
Notification::assertSentTo(
$user,
OrderShipped::class,
function ($notification, $channels) use ($order) {
return $notification->order->id === $order->id;
}
);
// 斷言通知已經發送給了指定用戶...
Notification::assertSentTo(
[$user], OrderShipped::class
);
// 斷言通知沒有發送...
Notification::assertNotSentTo(
[$user], AnotherNotification::class
);
}
}
<a name="queue-fake"></a>
## 隊列模擬
你可以使用 `Queue` facade 的 `fake` 方法來模擬任務隊列,測試的時候并不會真的把任務放入隊列。然后你可以斷言任務被放進了隊列,甚至可以檢查它們收到的數據。使用 fakes 的時候,斷言一般出現在測試代碼的后面。
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Jobs\ShipOrder;
use Illuminate\Support\Facades\Queue;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
public function testOrderShipping()
{
Queue::fake();
// 處理訂單發貨...
Queue::assertPushed(ShipOrder::class, function ($job) use ($order) {
return $job->order->id === $order->id;
});
// 斷言任務進入了指定隊列...
Queue::assertPushedOn('queue-name', ShipOrder::class);
// 斷言任務進入了2次...
Queue::assertPushed(ShipOrder::class, 2);
// 斷言任務沒有進入隊列...
Queue::assertNotPushed(AnotherJob::class);
}
}
<a name="storage-fake"></a>
## Storage 模擬
利用 `Storage` facade 的 `fake` 方法,你可以輕松地生成一個模擬的磁盤,結合 `UploadedFile` 類的文件生成工具,極大地簡化了文件上傳測試。例如:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class ExampleTest extends TestCase
{
public function testAvatarUpload()
{
Storage::fake('avatars');
$response = $this->json('POST', '/avatar', [
'avatar' => UploadedFile::fake()->image('avatar.jpg')
]);
// 斷言文件已存儲
Storage::disk('avatars')->assertExists('avatar.jpg');
// 斷言文件不存在
Storage::disk('avatars')->assertMissing('missing.jpg');
}
}
<a name="mocking-facades"></a>
## Facades 模擬
不同于傳統的靜態函數的調用, [facades](/docs/{{version}}/facades) 也是可以被模擬的,相對靜態函數來說這是個巨大的優勢,即使你在使用依賴注入,測試時依然會非常方便。在很多測試中,你可能經常想在控制器中模擬對 Laravel facade 的調用。比如下面控制器中的行為:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Cache;
class UserController extends Controller
{
/**
* 顯示網站的所有用戶
*
* @return Response
*/
public function index()
{
$value = Cache::get('key');
//
}
}
我們可以通過 `shouldReceive` 方法來模擬 `Cache` facade ,此函數會返回一個 [Mockery](https://github.com/padraic/mockery) 實例,由于對 facade 的調用實際上都是由 Laravel 的 [服務容器](/docs/{{version}}/container) 管理的,所以 facade 能比傳統的靜態類表現出更好的測試便利性。接下來,讓我們來模擬一下 `Cache` facade 的 `get` 方法的調用:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
class UserControllerTest extends TestCase
{
public function testGetIndex()
{
Cache::shouldReceive('get')
->once()
->with('key')
->andReturn('value');
$response = $this->get('/users');
// ...
}
}
> {note} 不可以模擬 `Request` facade,測試時,如果需要傳遞指定的數據請使用 HTTP 輔助函數,例如 `get` 和 `post`。類似的,請在你的測試中通過調用 `Config::set` 來模擬 `Config` facade。
---
> {note} 歡迎任何形式的轉載,但請務必注明出處,尊重他人勞動共創開源社區。
>
> 轉載請注明:本文檔由 Laravel China 社區 [laravel-china.org](https://laravel-china.org) 組織翻譯,詳見 [翻譯召集帖](https://laravel-china.org/topics/5756/laravel-55-document-translation-call-come-and-join-the-translation)。
>
> 文檔永久地址: https://d.laravel-china.org
- 說明
- 翻譯說明
- 發行說明
- 升級說明
- 貢獻導引
- 入門指南
- 安裝
- 配置信息
- 文件夾結構
- HomeStead
- Valet
- 核心架構
- 請求周期
- 服務容器
- 服務提供者
- 門面(Facades)
- Contracts
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- 重定向
- Session
- 表單驗證
- 錯誤與日志
- 前端開發
- Blade 模板
- 本地化
- 前端指南
- 編輯資源 Mix
- 安全
- 用戶認證
- API認證
- 用戶授權
- 加密解密
- 哈希
- 重置密碼
- 綜合話題
- Artisan 命令行
- 廣播系統
- 緩存系統
- 集合
- 事件系統
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 模型關聯
- Eloquent 集合
- 修改器
- API 資源
- 序列化
- 測試
- 快速入門
- HTTP 測試
- 瀏覽器測試 Dusk
- 數據庫測試
- 測試模擬器
- 官方擴展包
- Cashier 交易工具包
- Envoy 部署工具
- Horizon
- Passport OAuth 認證
- Scout 全文搜索
- Socialite 社交化登錄
- 交流說明