0
0
Laravelframework~8 mins

Mocking and faking in Laravel - Performance & Optimization

Choose your learning style9 modes available
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.