Laravel TDD Tutorial: Test-Driven Development in PHP

Laravel TDD Tutorial: Test-Driven Development in PHP

Test-driven development is not a testing technique — it's a design technique. Writing the test before the code forces you to think about the interface before the implementation, which consistently produces more focused, composable code. In Laravel, the tooling for TDD is first-class: PHPUnit is built in, Mockery ships with the framework, and the factory system makes test data fast to set up.

This tutorial walks through TDD from the first failing test through working, refactored code.

The Red-Green-Refactor Cycle

TDD has three phases:

  1. Red — Write a test that describes the behavior you want. Run it. It fails. This is correct — the code doesn't exist yet.
  2. Green — Write the minimum code to make the test pass. Don't design. Don't optimize. Make it green.
  3. Refactor — Clean up the implementation without breaking the tests. Extract methods, rename variables, eliminate duplication.

The cycle repeats for every behavior you add. Keeping cycles short (minutes, not hours) is the discipline that makes TDD work.

Starting with a Failing Test

We'll build an invoice calculation feature. Start with the simplest test case.

php artisan make:test InvoiceCalculatorTest --unit

Write the first test — before any implementation exists:

<?php

namespace Tests\Unit;

use App\Services\InvoiceCalculator;
use PHPUnit\Framework\TestCase;

class InvoiceCalculatorTest extends TestCase
{
    public function test_calculates_subtotal_from_line_items(): void
    {
        $calculator = new InvoiceCalculator();

        $subtotal = $calculator->subtotal([
            ['quantity' => 2, 'unit_price' => 50.00],
            ['quantity' => 1, 'unit_price' => 30.00],
        ]);

        $this->assertEquals(130.00, $subtotal);
    }
}

Run it:

php artisan test tests/Unit/InvoiceCalculatorTest.php

It fails with Class "App\Services\InvoiceCalculator" not found. That's red. Now write the minimum code to pass:

<?php

namespace App\Services;

class InvoiceCalculator
{
    public function subtotal(array $lineItems): float
    {
        return array_sum(array_map(
            fn ($item) => $item['quantity'] * $item['unit_price'],
            $lineItems
        ));
    }
}

Green. Now add the next test — don't touch the implementation yet:

public function test_applies_percentage_discount(): void
{
    $calculator = new InvoiceCalculator();

    $total = $calculator->totalWithDiscount(
        subtotal: 100.00,
        discountPercent: 10
    );

    $this->assertEquals(90.00, $total);
}

Red. Implement:

public function totalWithDiscount(float $subtotal, int $discountPercent): float
{
    return $subtotal * (1 - $discountPercent / 100);
}

Green. Add tax:

public function test_applies_tax_after_discount(): void
{
    $calculator = new InvoiceCalculator();

    $total = $calculator->totalWithTax(
        subtotal: 100.00,
        discountPercent: 10,
        taxPercent: 20
    );

    // 100 → 90 after 10% discount → 108 after 20% tax
    $this->assertEquals(108.00, $total);
}

Implement:

public function totalWithTax(float $subtotal, int $discountPercent, int $taxPercent): float
{
    $discounted = $this->totalWithDiscount($subtotal, $discountPercent);
    return $discounted * (1 + $taxPercent / 100);
}

Green. Now refactor — the method signatures are a bit awkward. You could introduce a value object:

// After refactor
$invoice = new Invoice(
    lineItems: $items,
    discountPercent: 10,
    taxPercent: 20,
);

$total = $calculator->calculate($invoice);

Run tests after refactoring. If they're still green, the refactor was safe.

Mocking with Mockery

TDD gets more interesting when units have dependencies. A service that sends invoices via email shouldn't actually send email during tests. That's where Mockery comes in.

Laravel includes Mockery — it integrates with PHPUnit via the CreatesApplication trait that tears down mock expectations after each test.

Suppose the invoice service depends on a mailer:

<?php

namespace App\Services;

interface InvoiceMailer
{
    public function send(Invoice $invoice, string $recipient): bool;
}

class InvoiceService
{
    public function __construct(private InvoiceMailer $mailer) {}

    public function issue(Invoice $invoice, string $recipient): void
    {
        if (!$this->mailer->send($invoice, $recipient)) {
            throw new \RuntimeException('Failed to deliver invoice.');
        }

        $invoice->markAsIssued();
    }
}

Write the test using Mockery:

<?php

namespace Tests\Unit;

use App\Models\Invoice;
use App\Services\InvoiceMailer;
use App\Services\InvoiceService;
use Mockery;
use Tests\TestCase;

class InvoiceServiceTest extends TestCase
{
    public function test_issues_invoice_when_email_succeeds(): void
    {
        $invoice = Mockery::mock(Invoice::class);
        $invoice->shouldReceive('markAsIssued')->once();

        $mailer = Mockery::mock(InvoiceMailer::class);
        $mailer->shouldReceive('send')
               ->once()
               ->with($invoice, 'client@example.com')
               ->andReturn(true);

        $service = new InvoiceService($mailer);
        $service->issue($invoice, 'client@example.com');

        // Mockery verifies expectations on teardown
    }

    public function test_throws_when_email_fails(): void
    {
        $invoice = Mockery::mock(Invoice::class);
        $invoice->shouldNotReceive('markAsIssued');

        $mailer = Mockery::mock(InvoiceMailer::class);
        $mailer->shouldReceive('send')->andReturn(false);

        $service = new InvoiceService($mailer);

        $this->expectException(\RuntimeException::class);
        $this->expectExceptionMessage('Failed to deliver invoice.');

        $service->issue($invoice, 'client@example.com');
    }
}

Note the shouldReceive('markAsIssued')->once() in the first test and shouldNotReceive('markAsIssued') in the second. Mockery validates these expectations — if markAsIssued is called when it shouldn't be, or not called when it should, the test fails.

Testing Eloquent Models

Eloquent models have behavior worth testing — scopes, accessors, mutators, relationships. Test them against a real database.

php artisan make:test InvoiceModelTest --unit

Use RefreshDatabase to get a clean state:

<?php

namespace Tests\Unit;

use App\Models\Invoice;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class InvoiceModelTest extends TestCase
{
    use RefreshDatabase;

    public function test_scope_pending_filters_correctly(): void
    {
        Invoice::factory()->count(3)->pending()->create();
        Invoice::factory()->count(2)->paid()->create();

        $pending = Invoice::pending()->get();

        $this->assertCount(3, $pending);
        $this->assertTrue($pending->every(fn ($i) => $i->status === 'pending'));
    }

    public function test_total_accessor_sums_line_items(): void
    {
        $invoice = Invoice::factory()->create();

        $invoice->lineItems()->createMany([
            ['description' => 'Design', 'quantity' => 1, 'unit_price' => 500],
            ['description' => 'Dev',    'quantity' => 2, 'unit_price' => 200],
        ]);

        $this->assertEquals(900.00, $invoice->total);
    }

    public function test_belongs_to_user(): void
    {
        $user = User::factory()->create();
        $invoice = Invoice::factory()->for($user)->create();

        $this->assertTrue($invoice->user->is($user));
    }

    public function test_mark_as_paid_sets_status_and_timestamp(): void
    {
        $invoice = Invoice::factory()->pending()->create();

        $invoice->markAsPaid();

        $this->assertEquals('paid', $invoice->fresh()->status);
        $this->assertNotNull($invoice->fresh()->paid_at);
    }
}

Writing Tests for Existing Code

TDD ideally means tests come first. In practice, you'll often add tests to existing code — when adding a feature, fixing a bug, or increasing coverage before a refactor.

The discipline when adding tests to existing code:

  1. Write a test that covers the behavior you're changing
  2. Verify the test passes (it should, since the code exists)
  3. Make your change — the test should still pass, or fail in an expected way

For bug fixes, write a test that reproduces the bug first:

public function test_discount_cannot_exceed_subtotal(): void
{
    // This test was added when we discovered discounts could go negative
    $calculator = new InvoiceCalculator();

    $total = $calculator->totalWithDiscount(
        subtotal: 50.00,
        discountPercent: 120 // 120% discount
    );

    // Should clamp at 0, not go negative
    $this->assertEquals(0.00, $total);
}

Write it, watch it fail (reproducing the bug), fix the code, watch it pass. Now the regression can never reappear silently.

Partial Mocks

When you need to mock only some methods on a real class:

$calculator = Mockery::mock(InvoiceCalculator::class)->makePartial();
$calculator->shouldReceive('taxRate')->andReturn(0.20);

// subtotal() uses real implementation
// taxRate() returns the mocked value

Spies

Spies are mocks that don't set expectations upfront — you verify after the fact:

$mailer = Mockery::spy(InvoiceMailer::class);

$service = new InvoiceService($mailer);
$service->issue($invoice, 'client@example.com');

$mailer->shouldHaveReceived('send')
       ->once()
       ->with($invoice, 'client@example.com');

Spies read more naturally in some test styles — especially when you care more about outcomes than setting up expectations in advance.

Laravel's Built-in Fakes

For Laravel-specific infrastructure (queues, events, mail, notifications), use the built-in fakes rather than Mockery mocks:

public function test_issuing_invoice_dispatches_event(): void
{
    Event::fake();

    $invoice = Invoice::factory()->create();
    $invoice->markAsIssued();

    Event::assertDispatched(InvoiceIssued::class, fn ($event) =>
        $event->invoice->is($invoice)
    );
}

public function test_payment_received_sends_notification(): void
{
    Notification::fake();

    $user = User::factory()->create();
    $invoice = Invoice::factory()->for($user)->create();
    $invoice->recordPayment(500.00);

    Notification::assertSentTo($user, PaymentReceived::class);
}

These fakes integrate cleanly with the rest of your test suite and reset between tests automatically.

Structuring Your TDD Workflow

The practical TDD loop in a terminal:

# Watch mode — re-run tests on file change (requires phpunit-watcher or Pest's --watch)
./vendor/bin/pest --watch

# Or run a specific test file repeatedly
php artisan test tests/Unit/InvoiceCalculatorTest.php

# Check coverage as you go
php artisan test --coverage --min=80

The goal isn't 100% coverage — it's coverage of behavior that matters. Every business rule, every edge case, every error path. Coverage of implementation details (private helper methods, simple getters) adds noise without adding confidence.

When your codebase has thorough TDD coverage, HelpMeTest extends that confidence to production — running key user flows continuously so you know the moment a live deployment breaks something your unit tests couldn't catch.

Read more

Start now free