0
0
Laravelframework~30 mins

Mocking and faking in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Mocking and Faking in Laravel Testing
📖 Scenario: You are building a Laravel application that sends welcome emails to new users. To ensure your email sending logic works correctly without actually sending emails during tests, you will use Laravel's mocking and faking features.
🎯 Goal: Build a simple Laravel test that fakes the mail sending and verifies that the welcome email is sent when a new user is created.
📋 What You'll Learn
Create a User model instance with specific attributes
Fake the mail sending using Laravel's Mail facade
Trigger the welcome email sending logic
Assert that the welcome email was sent to the correct user
💡 Why This Matters
🌍 Real World
In real Laravel applications, you want to test email sending without actually sending emails. Mocking and faking mail helps you verify your code works safely and quickly.
💼 Career
Understanding mocking and faking is essential for Laravel developers to write reliable automated tests, which is a key skill in professional software development.
Progress0 / 4 steps
1
Create a User instance
Create a variable called $user that holds a new User instance with the name set to 'John Doe' and email set to 'john@example.com'.
Laravel
Need a hint?

Use new User([...]) to create the user instance with the exact attributes.

2
Fake the Mail facade
Add the line \Illuminate\Support\Facades\Mail::fake(); at the start of the test_welcome_email_is_sent method to fake mail sending.
Laravel
Need a hint?

Use Mail::fake(); to prevent actual emails from being sent during the test.

3
Trigger the welcome email sending
Call the method sendWelcomeEmail() on the $user variable to simulate sending the welcome email.
Laravel
Need a hint?

Call sendWelcomeEmail() on the $user variable to trigger the email logic.

4
Assert the welcome email was sent
Add an assertion using Mail::assertSent() to check that the App\Mail\WelcomeMail was sent to 'john@example.com'.
Laravel
Need a hint?

Use Mail::assertSent(WelcomeMail::class, fn($mail) => $mail->hasTo('john@example.com')); to check the email was sent.