0
0
Laravelframework~3 mins

Why Mocking and faking in Laravel? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how pretending services work can save hours of testing headaches!

The Scenario

Imagine testing your Laravel app that sends emails or talks to a payment service. You have to wait for real emails or real payments every time you run tests.

The Problem

Manually waiting for real services makes tests slow and flaky. Sometimes external services fail or cost money. It's hard to test all cases reliably.

The Solution

Mocking and faking let you pretend those services work perfectly or fail on purpose. This way, tests run fast and always behave the same.

Before vs After
Before
$response = $this->post('/pay', ['amount' => 100]); // actually calls payment API
$this->assertTrue($response->successful());
After
Payment::fake();
$response = $this->post('/pay', ['amount' => 100]);
Payment::assertCharged(100);
What It Enables

It enables fast, reliable tests that simulate real-world scenarios without depending on external services.

Real Life Example

When testing user registration, you fake sending a welcome email instead of sending a real one, so tests run instantly and don't spam inboxes.

Key Takeaways

Manual testing with real services is slow and unreliable.

Mocking and faking simulate services for fast, stable tests.

This helps catch bugs early without extra costs or delays.