* * * * *
[TOC]
## 簡介
在 Laravel 應用程序測試中,你可能希望「模擬」應用程序的某些功能的行為,從而避免該部分在測試中真正執行。例如:在控制器執行過程中會觸發事件(Event),從而避免該事件在測試控制器時真正執行。這允許你在僅測試控制器 HTTP 響應的情況時,而不必擔心觸發事件。當然,你也可以在單獨的測試中測試該事件邏輯。
Laravel 針對事件、任務和 Facades 的模擬,提供了開箱即用的輔助函數。這些函數基于 Mocker 封裝而成,使用非常方便,無需手動調用復雜的 Mockery 函數。當然你也可以使用?[Mockery](http://docs.mockery.io/en/latest/)?或者使用 PHPUnit 創建自己的模擬器。
## 任務模擬
~~~
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Jobs\ShipOrder;
use Illuminate\Support\Facades\Bus;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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);
}
}
~~~
## 事件模擬
你可以使用?`Event`?Facade 的?`fake`?方法來模擬事件監聽,測試的時候并不會真正觸發事件監聽器。然后你就可以測試斷言事件運行了,甚至可以檢查他們接收的數據。使用 fake 的時候,斷言一般出現在測試代碼的后面:
~~~
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Events\OrderShipped;
use App\Events\OrderFailedToShip;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
class ExampleTest extends TestCase
{
/**
* 測試訂單發貨
*/
public function testOrderShipping()
{
Event::fake();
// 處理訂單發貨...
Event::assertDispatched(OrderShipped::class, function ($e) use ($order) {
return $e->order->id === $order->id;
});
// 斷言事件執行兩次...
Event::assertDispatched(OrderShipped::class, 2);
// 斷言事件并沒有被執行...
Event::assertNotDispatched(OrderFailedToShip::class);
}
}
~~~
## 郵件模擬
你可以是用?`Mail`?Facade 的?`fake`?方法來模擬郵件發送,測試時不會真的發送郵件,然后你可以斷言?[mailables](http://www.hmoore.net/tonyyu/laravel_5_6/786245)?發送給了用戶,甚至可以檢查他們收到的內容。使用 fakes 時,斷言一般放在測試代碼的后面:
~~~
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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('...');
});
// 斷言郵件被發送兩次...
Mail::assertSent(OrderShipped::class, 2);
// 斷言沒有發送郵件...
Mail::assertNotSent(AnotherMailable::class);
}
}
~~~
如果你用后臺任務執行郵件發送隊列,你應該是用?`assertQueued`?代替?`assertSent`?:
~~~
Mail::assertQueued(...);
Mail::assertNotQueued(...);
~~~
## 通知模擬
你可以使用?`Notification`?Facade 的?`fake`?方法來模擬通知的發送,測試時并不會真的發出通知。然后你可以斷言?[notifications](http://www.hmoore.net/tonyyu/laravel_5_6/786246)?發送給了用戶,甚至可以檢查他們收到的內容。使用 fakes 時,斷言一般放在測試代碼后面:
~~~
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Notifications\OrderShipped;
use Illuminate\Support\Facades\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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
);
}
}
~~~
## 隊列模擬
你可以使用?`Queue`?Facade 的?`fake`?方法來模擬任務隊列,測試的時候并不會真的把任務放入隊列。然后你可以斷言任務被放入了隊列,甚至可以檢查他們收到的內容。使用 fakes 時,斷言一般放在測試代碼的后面:
~~~
<?php
namespace Tests\Feature;
use Tests\TestCase;
use App\Jobs\ShipOrder;
use Illuminate\Support\Facades\Queue;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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);
}
}
~~~
## 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\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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');
}
}
~~~
> {tip} 默認情況下,`fake`?方法將刪除臨時目錄下所有文件。如果你想保留這些文件,你可以使用 「persistentFake」。
## Facades
與傳統的靜態方法調用,不同?[facades](http://www.hmoore.net/tonyyu/laravel_5_6/786058)?也可以被模擬。相對靜態函數調用來說這是一個巨大的優勢,即時你在使用依賴注入,測試時依然非常方便。在測試中,你可能想在控制器中模擬對 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 的?[服務容器](http://www.hmoore.net/tonyyu/laravel_5_6/786056)?管理的,所以 Facade 能比傳統的靜態類表現出更好的測試便利性。下面,讓我們模擬一下?`Cache`?Facade 的?`get`?方法:
~~~
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Support\Facades\Cache;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithoutMiddleware;
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。
- 前言
- 翻譯說明
- 發行說明
- 升級指南
- 貢獻導引
- 入門指南
- 安裝
- 配置信息
- 文件夾結構
- Homestead
- Valet
- 部署
- 核心架構
- 請求周期
- 服務容器
- 服務提供者
- Facades
- Contracts
- 基礎功能
- 路由
- 中間件
- CSRF 保護
- 控制器
- 請求
- 響應
- 視圖
- URL
- Session
- 表單驗證
- 錯誤
- 日志
- 前端開發
- Blade 模板
- 本地化
- 前端指南
- 編輯資源 Mix
- 安全相關
- 用戶認證
- Passport OAuth 認證
- 用戶授權
- 加密解密
- 哈希
- 重置密碼
- 綜合話題
- Artisan 命令行
- 廣播系統
- 緩存系統
- 集合
- 事件系統
- 文件存儲
- 輔助函數
- 郵件發送
- 消息通知
- 擴展包開發
- 隊列
- 任務調度
- 數據庫
- 快速入門
- 查詢構造器
- 分頁
- 數據庫遷移
- 數據填充
- Redis
- Eloquent ORM
- 快速入門
- 模型關聯
- Eloquent 集合
- 修改器
- API 資源
- 序列化
- 測試相關
- 快速入門
- HTTP 測試
- 瀏覽器測試 Dusk
- 數據庫測試
- 測試模擬器
- 官方擴展包
- Cashier 交易工具包
- Envoy 部署工具
- Horizon
- Scout 全文搜索
- Socialite 社會化登錄