Laravel interview question · Most asked
How do you test a Laravel application? Feature tests, unit tests and fakes.
Summary
Feature tests send HTTP requests through the whole framework ($this->postJson('/api/orders', ...)->assertCreated()); unit tests cover isolated classes. Laravel's fakes (Queue::fake(), Mail::fake(), Http::fake(), Event::fake(), Storage::fake()) replace side effects so tests are fast and deterministic.
Longer Answer
- Use
RefreshDatabase(wraps each test in a transaction, or migrates once) with a real database engine where possible; SQLite in memory is fast but behaves differently from MySQL or PostgreSQL (JSON, locking, strictness). - Factories create the exact records a test needs.
actingAs($user)authenticates; assert authorization by calling endpoints as the wrong user and expecting 403/404.Http::fake([...])plusHttp::preventStrayRequests()ensure no test calls a real external API.Queue::fake()thenQueue::assertPushed(SendInvoice::class, fn ($job) => ...).- Time:
$this->travel(5)->minutes()orCarbon::setTestNow().
Most value comes from feature tests of real endpoints; unit-test complex domain logic separately.
Key Points
- Feature tests through HTTP; unit tests for logic.
- Fakes for queue, mail, HTTP, events, storage.
RefreshDatabase; beware SQLite differences.preventStrayRequests().
Explanation
What interviewers look for
A pragmatic testing strategy that includes authorization tests and isolates external services.
Follow-up questions
- How do you test a queued job's behaviour, not just that it was dispatched?
More most-asked Laravel questions
- How do you validate requests in Laravel? Why use Form Requests?
- Gates or policies: how does authorization work in Laravel?
- What is mass assignment, and how do $fillable and $guarded protect against it?
- How do database transactions work in Laravel, and what pitfalls should you know?
- Which Artisan commands would you run when deploying Laravel to production, and why?
- What is the service container, and how does dependency injection work in Laravel?
- What is the N+1 query problem in Eloquent and how do you prevent it?
- How do queues work in Laravel?