Bird
Raised Fist0
Laravelframework~8 mins

Mocking and faking in Laravel - Performance & Optimization

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Performance: Mocking and faking
LOW IMPACT
Mocking and faking mainly affect test execution speed and resource usage during development, not the live page load or rendering.
Testing code that interacts with external services or databases
Laravel
<?php
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Event;

public function testUserCreationWithMock() {
  Http::fake(['api.example.com/*' => Http::response(['data' => 'fake'], 200)]);
  Event::fake();
  $user = User::factory()->create();
  $this->assertNotNull($user);
  $response = Http::get('https://api.example.com/data');
  $this->assertEquals(200, $response->status());
}
Mocks and fakes avoid real network and database calls, making tests fast and reliable.
📈 Performance GainReduces test runtime by seconds, avoids network latency and database overhead.
Testing code that interacts with external services or databases
Laravel
<?php
// Test calls real database or API
public function testUserCreation() {
  $user = User::create(['name' => 'Test']);
  $response = Http::get('https://api.example.com/data');
  $this->assertTrue($user->exists);
  $this->assertEquals(200, $response->status());
}
This test hits the real database and external API, making tests slow and flaky.
📉 Performance CostBlocks test execution for hundreds of milliseconds per call, slows CI pipelines.
Performance Comparison
PatternTest Execution TimeExternal CallsResource UsageVerdict
Real database and API callsHigh (slow)Many (network + DB)High (DB connections, network)[X] Bad
Using Laravel Http::fake and model factoriesLow (fast)None (all faked)Low (no real connections)[OK] Good
Rendering Pipeline
Mocking and faking do not affect browser rendering pipeline since they run in backend tests, not in the browser.
⚠️ Bottlenecknone
Optimization Tips
1Always fake external HTTP calls in tests to avoid network delays.
2Use model factories instead of real database inserts when possible for faster tests.
3Avoid hitting real services in tests to keep CI pipelines fast and reliable.
Performance Quiz - 3 Questions
Test your performance knowledge
Why should you use mocking and faking in Laravel tests?
ATo reduce CSS file size
BTo improve browser rendering speed
CTo speed up tests by avoiding real external calls
DTo increase database size
DevTools: No browser DevTools (backend testing)
How to check: Use PHPUnit or Pest test runner with timing output; check logs for external calls.
What to look for: Fast test execution times and absence of real network or database calls indicate good mocking.

Practice

(1/5)
1. What is the main purpose of mocking and faking in Laravel testing?
easy
A. To automatically generate user interfaces
B. To simulate external services without performing real actions
C. To permanently store test data in the database
D. To speed up the application in production

Solution

  1. Step 1: Understand mocking and faking concept

    Mocking and faking are used to imitate external services or actions during tests without actually performing them.
  2. Step 2: Identify the purpose in Laravel testing

    Laravel uses mocking and faking to avoid real side effects like sending emails or making HTTP requests during tests.
  3. Final Answer:

    To simulate external services without performing real actions -> Option B
  4. Quick Check:

    Mocking = simulate services [OK]
Hint: Mocking means faking external actions in tests [OK]
Common Mistakes:
  • Thinking mocking speeds up production
  • Confusing mocking with real data storage
  • Assuming mocking creates UI automatically
2. Which Laravel method correctly fakes sending emails in a test?
easy
A. Mail::fake();
B. Mail::sendFake();
C. Mail::mock();
D. Mail::simulate();

Solution

  1. Step 1: Recall Laravel's mail faking method

    Laravel provides the Mail::fake() method to fake email sending during tests.
  2. Step 2: Check method correctness

    Only Mail::fake() is the correct and existing method; others are invalid or do not exist.
  3. Final Answer:

    Mail::fake(); -> Option A
  4. Quick Check:

    Mail::fake() = correct syntax [OK]
Hint: Use Mail::fake() to fake emails in Laravel tests [OK]
Common Mistakes:
  • Using non-existent methods like Mail::sendFake()
  • Confusing mock() with fake()
  • Forgetting the parentheses ()
3. What will the following Laravel test code output?
use Illuminate\Support\Facades\Http;

Http::fake();

$response = Http::get('https://example.com/api');

return $response->status();
medium
A. null
B. 404
C. 500
D. 200

Solution

  1. Step 1: Understand Http::fake() behavior

    Http::fake() fakes all HTTP requests and returns a default successful response with status 200.
  2. Step 2: Analyze the returned status code

    The $response->status() returns 200 because the fake response simulates success.
  3. Final Answer:

    200 -> Option D
  4. Quick Check:

    Http::fake() returns 200 status [OK]
Hint: Http::fake() returns 200 status by default [OK]
Common Mistakes:
  • Assuming fake returns 404 or error
  • Expecting null instead of response object
  • Confusing Http::fake() with real HTTP call
4. Identify the error in this Laravel test code snippet:
use Illuminate\Support\Facades\Storage;

Storage::fake('local');

Storage::put('file.txt', 'Hello');

$this->assertTrue(Storage::exists('file.txt'));
medium
A. Storage::fake() must be called with 'public' disk, not 'local'
B. Storage::exists() should be Storage::disk('local')->exists()
C. No error, the code is correct
D. Storage::put() cannot be used after Storage::fake()

Solution

  1. Step 1: Understand Storage::fake() usage

    Storage::fake('local') fakes the 'local' disk, which is Laravel's default disk.
  2. Step 2: Check method calls for disk specification

    Storage::put() and Storage::exists() use the default disk ('local'), so they interact with the faked disk correctly. The assertion passes.
  3. Final Answer:

    No error, the code is correct -> Option C
  4. Quick Check:

    Default disk = 'local' [OK]
Hint: Storage:: methods use default disk after Storage::fake('local') [OK]
Common Mistakes:
  • Thinking disk must always be explicitly specified
  • Believing Storage::put() is disallowed after fake
  • Confusing required disk names
5. You want to test that your Laravel app sends exactly one notification to a user without actually sending it. Which approach correctly achieves this?
hard
A. Use Notification::fake() and then assertNotificationSent()
B. Use Notification::send() and check the database for records
C. Use Notification::mock() and assertNothingSent()
D. Use Notification::fake() and then assertNothingSent()

Solution

  1. Step 1: Choose the correct faking method for notifications

    Notification::fake() prevents real notifications from sending and allows assertions.
  2. Step 2: Use the right assertion to check one notification sent

    assertNotificationSent() verifies that a notification was sent exactly once to the user.
  3. Final Answer:

    Use Notification::fake() and then assertNotificationSent() -> Option A
  4. Quick Check:

    Notification::fake() + assertNotificationSent() = test notifications [OK]
Hint: Fake notifications, then assertNotificationSent() to check sends [OK]
Common Mistakes:
  • Using assertNothingSent() when expecting a notification
  • Trying to check notifications via database records
  • Using non-existent Notification::mock() method