PHPUnit 自動化測試大作戰【CH19】

更新 發佈閱讀 18 分鐘

今天來看 Mail Mocking 吧!

Mail Mocking 函數

  • Mail::fake():當我們希望在執行測試目標行為時, 想驗證是否有觸發到發送 Email ,但又不要真的觸發 Email 的寄送時,可在測試程式碼中呼叫此函數。
  • Mail::assertSent():可驗證指定的 Mailable 類別是否會被觸發寄送。需在執行 Mail::fake() 後方可使用。
  • Mail::assertNotSent()。可驗證指定的 Mailable 類別是否不會被觸發寄送。需在執行 Mail::fake() 後方可使用。
  • Mail::assertNothingSent()。可驗證是否無 Mailable 類別被觸發寄送。需在執行 Mail::fake() 後方可使用。

其中值得注意的是,Mail::assertSent()還有更細緻的測試方式:

Mail::assertSent(MailableClass::class, function ($mail) use ($user) {

return $mail->hasTo($user->email) &&

$mail->hasCc('...') &&

$mail->hasBcc('...') &&

$mail->hasReplyTo('...') &&

$mail->hasFrom('...') &&

$mail->hasSubject('...');

});
  • $mail→hasTo:驗證收件人。
  • $mail→hasCc:驗證副本收件人。
  • $mail→hasBcc:驗證密件副本收件人。
  • $mail→hasReplyTo:驗證該信是否為回覆給指定收件人之回信。
  • $mail->hasFrom:驗證寄件人。
  • $mail->hasSubject:驗證信件主旨。

接下來讓我們實際演練看看吧!

範例

測試目標:忘記密碼信索取端點

  • database/migrations/2014_10_12_000000_create_users_table.php
<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

return new class extends Migration{

/** * Run the migrations. * * @return void */

public function up() {

Schema::create('users', function (Blueprint $table) {

$table->id();

$table->string('name');

$table->string('email')->unique();

$table->timestamp('email_verified_at')->nullable();

$table->string('password');

$table->string('forget_password_token', 128)->nullable();

$table->rememberToken();

$table->timestamps();

}); } /** * Reverse the migrations. * * @return void */

public function down() {

Schema::dropIfExists('users');

}};
  • app/Models/User.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable{

use HasApiTokens, HasFactory, Notifiable;

/** * The attributes that are mass assignable. * * @var array<int, string> */

protected $fillable = [

'name',

'email',

'password',

'forget_password_token',

]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */

protected $hidden = [

'password',

'remember_token',

]; /** * The attributes that should be cast. * * @var array<string, string> */

protected $casts = [

'email_verified_at' => 'datetime',

];}
  • database/factories/UserFactory.php
<?php

namespace Database\Factories;

use Illuminate\Support\Str;

use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory{

/** * Define the model's default state. * * @return array */

public function definition(): array {

return [

'name' => $this->faker->name,

'email' => $this->faker->safeEmail,

'email_verified_at' => $this->faker->dateTime(),

'password' => bcrypt($this->faker->password),

'remember_token' => Str::random(10),

'forget_password_token' => Str::random(128),

]; }}
  • app/Mail/ForgetPasswordMail.php
<?php

namespace App\Mail;

use App\Models\User;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

class ForgetPasswordMail extends Mailable{

use Queueable, SerializesModels;

private $user;

/** * Create a new message instance. * * @return void */

public function __construct(User $user) {

$this->user = $user;

} /** * Build the message. * * @return $this */

public function build() {

$resetLink = config('app.url')

. "/password-reset?forget_password_token={$this->user->forget_password_token}";

return $this

->subject('To reset password')

->from('example@example.com', 'Example')

->with(['reset_link' => $resetLink])

->view('mail.forget-password-mail');

}}
  • resources/views/mail/forget-password-mail.blade.php
<!DOCTYPE html>

<html >

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Password Reset Mail</title>

</head>

<body class="antialiased">

<a href="{{ $reset_link }}">Reset Password</a>

</body>

</html>
  • routes\api.php
<?php

use App\Models\User;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Mail;

use Illuminate\Support\Facades\Route;

use App\Mail\ForgetPasswordMail;

Route::post('/forget-password-mail', function (Request $request) {

$email = $request->input('email');

$user = User::where('email', '=', $email)->first();

if (empty($user)) {

return response()->json([], 404);

} $user->forget_password_token = Str::random(128);

$user->save();

Mail::to($email)

->cc('cc@test.test')

->bcc('bcc@test.test')

->send(new ForgetPasswordMail($user));

return response('', 200);

})->name('retrieve-forget-password-mail');
  • 測試程式碼:
<?php

namespace Tests\Feature;

use App\Mail\ForgetPasswordMail;

use App\Models\User;

use Illuminate\Foundation\Testing\RefreshDatabase;

use Illuminate\Support\Facades\Mail;

use Tests\TestCase;

class MailTest extends TestCase{

use RefreshDatabase;

public function testRetriveForgetPasswordMailSuccess() {

$user = User::factory()->create();

$data = [

'email' => $user->email,

]; Mail::fake();

$response = $this->post(route('retrieve-forget-password-mail'), $data);

$response->assertOk();

Mail::assertSent(ForgetPasswordMail::class, function ($mail) use ($user) {

return $mail->hasTo($user->email);

}); } public function testRetriveForgetPasswordMailFailed() {

$user = User::factory()->create();

$data = [

'email' => $user->email . 'x',

]; Mail::fake();

$response = $this->post(route('retrieve-forget-password-mail'), $data);

$response->assertNotFound();

Mail::assertNotSent(ForgetPasswordMail::class);

}}

以上測試程式碼,測試了 2 種測試案例:

  • testRetriveForgetPasswordMailSuccess():在這個測試案例函數中,我們驗證了當忘記密碼信索取端點被請求時,若使用者帳號確實存在時,是否會觸發忘記密碼信 ForgotPasswordMail 寄出。
  • testRetriveForgetPasswordMailFailed():在這個測試案例函數中,我們驗證了當忘記密碼信索取端點被請求時,若使用者帳號不存在時,是否不會觸發忘記密碼信 ForgotPasswordMail 寄出。

以上就是今天所介紹的 Event Mocking,大家可以多加演練。

下一篇讓我們來看看 Queue Mocking。

如果您喜歡這篇文章,歡迎加入追蹤以接收新文章通知 😄

參考資料

本系列文章目錄

留言
avatar-img
留言分享你的想法!
avatar-img
WilliamP的沙龍
13會員
573內容數
歡迎來到 WilliamP 的沙龍天地,在這裡將與各位讀者探討各種主題,包刮高中數學題庫、PHP開發經驗、LINE聊天機器人開發經驗、書摘筆記等,歡迎交流!
WilliamP的沙龍的其他內容
2023/12/18
在前一篇文章中,我們探討了多重資料庫連線情境下,Model 及 Database Assertion 的應對方式,不過實際上筆者認為比較有難度的,其實是 Migration 應對方式。 今天就讓我們來探討這部分吧! Migration 應對方式 對於多重資料庫連線這種情境,筆者實務上做過的對應
2023/12/18
在前一篇文章中,我們探討了多重資料庫連線情境下,Model 及 Database Assertion 的應對方式,不過實際上筆者認為比較有難度的,其實是 Migration 應對方式。 今天就讓我們來探討這部分吧! Migration 應對方式 對於多重資料庫連線這種情境,筆者實務上做過的對應
2023/12/18
今天讓我們探討「缺乏 Migration Files 與 Factory Files」的 Legacy 情境吧! 很多時候我們會遇到沒有 Migration Files 或 Factory Files 的 Legacy Codebase,原因大概有以下幾種: 該程式庫原本不是以 Laravel
2023/12/18
今天讓我們探討「缺乏 Migration Files 與 Factory Files」的 Legacy 情境吧! 很多時候我們會遇到沒有 Migration Files 或 Factory Files 的 Legacy Codebase,原因大概有以下幾種: 該程式庫原本不是以 Laravel
2023/12/18
在實務情境上,常會有在單一專案程式庫中,存取多個不同資料庫的使用情境,在這種情況下,我們通常會設置多個資料庫連線(Database Connection)設定。 在平常開發使用設很方便,但要做測試時就會發現一些問題: 在測試程式碼或 Seeder 中調用 factory() 時,都是在預設連線資
2023/12/18
在實務情境上,常會有在單一專案程式庫中,存取多個不同資料庫的使用情境,在這種情況下,我們通常會設置多個資料庫連線(Database Connection)設定。 在平常開發使用設很方便,但要做測試時就會發現一些問題: 在測試程式碼或 Seeder 中調用 factory() 時,都是在預設連線資
看更多
你可能也想看
Thumbnail
吸引力法則是互相的,頻率相近的兩方總會尋到彼此。香氛和你也是。
Thumbnail
吸引力法則是互相的,頻率相近的兩方總會尋到彼此。香氛和你也是。
Thumbnail
本文探討臺灣串流平臺的發展現況、競爭格局,並解析其帶來的經濟效應。透過美國電影協會(MPA)的講座內容,結合業界專家意見與生活觀察,文章揭示串流平臺如何影響內容製作, 同時討論臺灣有利的創作環境,包括自由的風氣和開放的政策,對於提升國家軟實力與國際影響力的重要性。
Thumbnail
本文探討臺灣串流平臺的發展現況、競爭格局,並解析其帶來的經濟效應。透過美國電影協會(MPA)的講座內容,結合業界專家意見與生活觀察,文章揭示串流平臺如何影響內容製作, 同時討論臺灣有利的創作環境,包括自由的風氣和開放的政策,對於提升國家軟實力與國際影響力的重要性。
Thumbnail
在這一章中,我們探討了 PHP 中的函數,包括函數的基本結構、不同的函數定義方式(如函數聲明、函數表達式、箭頭函數和匿名函數)以及如何呼叫函數。我們還討論了函數的參數處理方式,包括單個參數、多個參數、預設參數值和剩餘參數。此外,我們還介紹了函數的返回值,包括返回單個值、返回物件和返回函數的情況。
Thumbnail
在這一章中,我們探討了 PHP 中的函數,包括函數的基本結構、不同的函數定義方式(如函數聲明、函數表達式、箭頭函數和匿名函數)以及如何呼叫函數。我們還討論了函數的參數處理方式,包括單個參數、多個參數、預設參數值和剩餘參數。此外,我們還介紹了函數的返回值,包括返回單個值、返回物件和返回函數的情況。
Thumbnail
當我們架好站、WebService測試完,接著就是測試區域網路連線啦~
Thumbnail
當我們架好站、WebService測試完,接著就是測試區域網路連線啦~
Thumbnail
Function的使用方式
Thumbnail
Function的使用方式
Thumbnail
在日常生活和工作中,我們經常需要發送電子郵件來進行溝通和分享資訊。本文將介紹如何使用Python的pywin32模組連接到Outlook,並通過程式來自動發送郵件。
Thumbnail
在日常生活和工作中,我們經常需要發送電子郵件來進行溝通和分享資訊。本文將介紹如何使用Python的pywin32模組連接到Outlook,並通過程式來自動發送郵件。
Thumbnail
 程式開發,功能 :               本程式執行後,自動寄出email,寄出的內容可依照讀取的參數檔內容而決定
Thumbnail
 程式開發,功能 :               本程式執行後,自動寄出email,寄出的內容可依照讀取的參數檔內容而決定
Thumbnail
在C#程式開發中,有時候我們需要透過Outlook來發送郵件。這篇教學將會教你如何使用Microsoft.Office.Interop.Outlook來完成這個任務。
Thumbnail
在C#程式開發中,有時候我們需要透過Outlook來發送郵件。這篇教學將會教你如何使用Microsoft.Office.Interop.Outlook來完成這個任務。
追蹤感興趣的內容從 Google News 追蹤更多 vocus 的最新精選內容追蹤 Google News