Courses

Testing in Laravel 11: Advanced Level

Testing Emails and Notifications with Fake

Summary of this lesson:
- Use Mail::fake() and Notification::fake()
- Test email and notification sending
- Assert specific mail and notification classes
- Verify notification recipients
- Simulate communication testing

How do you test sending emails? In Laravel, the process of sending emails can be "faked."


Scenario Example

We continue the same topic from the previous lessons. You send mail or notifications to the admin user within a Job, dispatched from the Controller or anywhere else.

use App\Models\User;
use App\Models\Product;
use App\Mail\NewProductCreatedMail;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Notification;
use App\Notifications\NewProductCreatedNotification;
 
class NewProductNotifyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
 
public function __construct(private readonly Product $product)
{}
 
public function handle(): void
{
$admin = User::where('is_admin', true)->first();
 
Mail::to($admin->email)->send(new NewProductCreatedMail($this->product));
 
Notification::send($admin, new NewProductCreatedNotification($this->product));
}
}

Both mail and notifications are only created using an Artisan command, and nothing changes inside them.


The Test

Again, we start the test by making...

The full lesson is only for Premium Members.
Want to access all 31 lessons of this course? (74 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord