Testing in Laravel

Interview Questions: PHPUnit, Pest, and Mocking

Q1: What is the difference between Feature and Unit tests in Laravel?

Unit Tests: Test a small, isolated piece of code (like a single method) without touching the database or external services. Fast execution.

Feature Tests: Test a larger slice of the application, often starting from an HTTP request. They interact with the database, session, and other framework features.

Q2: How do you test code that interacts with external APIs?

Mocking: You should never hit real external APIs in your test suite.

Http::fake(): Laravel provides a fluent way to mock the HTTP client.

Http::fake([
    'github.com/*' => Http::response(['foo' => 'bar'], 200),
]);

Q3: What is Pest PHP?

Concept: A modern testing framework built on top of PHPUnit with a focus on simplicity and developer experience.

Syntax: It uses a functional, Jest-like syntax (it('does something', function () { ... })) which is often more readable than the class-based structure of PHPUnit.

Q4: How do you test database transactions?

RefreshDatabase Trait: This trait automatically wraps each test case in a database transaction. After the test finishes, the transaction is rolled back, leaving the database in its original state.

Benefit: It is much faster than migrating and resetting the database for every test.

Q5: What is Dusk?

Tool: Laravel Dusk provides an expressive, easy-to-use browser automation and testing API.

Usage: It uses a real Chrome browser (via ChromeDriver) to test JavaScript-heavy applications (SPA, Vue/React components) that cannot be tested with standard PHPUnit HTTP tests.

Q6: How do you assert that an event was dispatched?

Event Fake: Use Event::fake() to prevent actual event listeners from running.

Event::fake();

// Perform action...

Event::assertDispatched(OrderShipped::class, function ($e) use ($order) {
    return $e->order->id === $order->id;
});