PHP

Laravel 13 Unit Testing Examples: HTTP Tests and Mocking

Updated

Laravel PHP framework logo

A new Laravel 13 app already has a working test suite: PHPUnit 12, an in-memory SQLite database, and the testing environment, all configured before you write a line. Run it with:

php artisan test          # or: ./vendor/bin/phpunit

Worth knowing before you trust that suite: the tests run on SQLite while production almost certainly does not, and the two disagree about declared types, foreign keys and what ALTER TABLE will accept — which is where a green test run and a failed migration come from.

The dependency worth naming, because so many tutorials assume otherwise, is PHPUnit rather than Pest. From the skeleton’s composer.json:

phpunit=^12.5.12
pest=absent
mockery=^1.6
php=^8.3

The database is already configured — don’t configure it again

Half the advice on this subject tells you to create a testing database and a .env.testing. You do not need either. The shipped phpunit.xml includes these lines:

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="BCRYPT_ROUNDS" value="4"/>
    <env name="CACHE_STORE" value="array"/>
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>
    <env name="MAIL_MAILER" value="array"/>
    <env name="QUEUE_CONNECTION" value="sync"/>
    <env name="SESSION_DRIVER" value="array"/>
</php>

Every test therefore runs against a database that exists only in RAM and disappears when the process ends. BCRYPT_ROUNDS=4 is there because hashing dominates test time otherwise, and MAIL_MAILER=array means no test can send real mail by accident, even when .env points the application at a live transport such as Amazon SES. You can assert all of it from inside a test, which is the point of the fourth case below.

A feature test with RefreshDatabase

namespace Tests\Feature;

use App\Models\Book;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

class BookTest extends TestCase
{
    use RefreshDatabase;

    #[Test]
    public function it_stores_a_book(): void
    {
        $book = Book::factory()->create([
            'title' => 'The Catcher in the Rye',
            'author' => 'J.D. Salinger',
            'published_year' => 1951,
        ]);

        $this->assertDatabaseHas('books', ['id' => $book->id, 'title' => 'The Catcher in the Rye']);
        $this->assertDatabaseCount('books', 1);
    }

    #[Test]
    public function it_removes_a_deleted_book(): void
    {
        $book = Book::factory()->create();

        $book->delete();

        $this->assertDatabaseMissing('books', ['id' => $book->id]);
    }

    #[Test]
    public function the_database_is_empty_again_for_the_next_test(): void
    {
        $this->assertDatabaseCount('books', 0);
    }

    #[Test]
    public function it_uses_an_in_memory_sqlite_database(): void
    {
        $this->assertSame('sqlite', config('database.default'));
        $this->assertSame(':memory:', config('database.connections.sqlite.database'));
        $this->assertSame('testing', app()->environment());
    }

    public function testTheOldPrefixStyleStillRuns(): void
    {
        $this->assertTrue(true);
    }
}

The third method is the one that earns its place. RefreshDatabase wraps each test in a transaction and rolls it back, so a row created in it_stores_a_book is gone by the time the next test runs — asserted, not assumed. The last method is there to settle a common question: yes, PHPUnit 12 still runs testXxx()-prefixed methods.

HTTP tests and mocking, which is where the value is

Testing a model’s create() mostly tests Eloquent. Testing the route tests your application:

#[Test]
public function it_lists_books_alphabetically(): void
{
    Book::factory()->create(['title' => 'Zeno']);
    Book::factory()->create(['title' => 'Anna']);

    $this->getJson('/api/books')
        ->assertOk()
        ->assertJsonCount(2)
        ->assertJsonPath('0.title', 'Anna')
        ->assertJsonStructure([['id', 'title', 'author']]);
}

#[Test]
public function it_rejects_a_bad_isbn(): void
{
    $this->postJson('/api/books', ['isbn' => 'too-short', 'author' => 'Someone', 'published_year' => 1999])
        ->assertStatus(422)
        ->assertJsonValidationErrors(['isbn']);

    $this->assertDatabaseCount('books', 0);
}

assertJsonValidationErrors plus assertDatabaseCount(0) is the pattern worth copying: it proves the request was rejected and that nothing was written anyway.

For the collaborator that must never run in a test — a paid API, an SMS gateway — replace it in the container. The controller type-hints IsbnLookup; the test swaps it:

#[Test]
public function it_stores_a_book_without_touching_the_isbn_api(): void
{
    $this->mock(IsbnLookup::class, function ($mock) {
        $mock->shouldReceive('titleFor')
            ->once()
            ->with('9780316769488')
            ->andReturn('The Catcher in the Rye');
    });

    $this->postJson('/api/books', [
        'isbn' => '9780316769488', 'author' => 'J.D. Salinger', 'published_year' => 1951,
    ])->assertCreated()->assertJsonPath('title', 'The Catcher in the Rye');
}

The real IsbnLookup::titleFor() in this example throws RuntimeException('network call attempted in a test'), and a fifth test asserts that it does. That is how you prove the mock is actually taking effect instead of quietly not being used. For HTTP clients specifically, prefer Http::fake(); for mail, Mail::fake() and assertSent(). $this->mock() is the general case.

What the run looks like

PHPUnit 12.5.33 by Sebastian Bergmann and contributors.

Runtime:       PHP 8.5.8
Configuration: .../phpunit.xml

...........                                                       11 / 11 (100%)

Time: 00:00.185, Memory: 52.50 MB

Book (Tests\Feature\Book)
 ✔ It stores a book
 ✔ It removes a deleted book
 ✔ The database is empty again for the next test
 ✔ It uses an in memory sqlite database
 ✔ The old prefix style still runs

Book Api (Tests\Feature\BookApi)
 ✔ It lists books alphabetically
 ✔ It rejects a bad isbn
 ✔ It stores a book without touching the isbn api
 ✔ The real service would have blown up

OK (11 tests, 27 assertions)

The listing above omits two of the eleven tests: the skeleton’s own tests/Unit/ExampleTest.php and tests/Feature/ExampleTest.php, one test each, which the “11 tests” total includes.

Starting from composer create-project laravel/laravel, laravel-unit-test-examples.sh adds a Book model, controller and the test classes used above, then checks the dependency versions, the phpunit.xml values, the passing suite, the tests/Unit error and the laravel/pao line; it needs PHP 8.3 or later, Composer and network access, and involves no database server because the tests use in-memory SQLite.

The trap in tests/Unit

Put a database test in tests/Unit and accept the default import and you get an error that names nothing useful:

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;   // <- the default for tests/Unit

class WrongPlaceTest extends TestCase
{
    use RefreshDatabase;
    ...
}

1) Tests\Unit\WrongPlaceTest::it_tries_to_touch_the_database
Error: Call to a member function connection() on null

PHPUnit\Framework\TestCase never boots the Laravel application, so there is no container, no configuration and no database connection — hence null. The rule is simple: anything needing the framework goes in tests/Feature and extends Tests\TestCase; tests/Unit is for classes you can construct with new.

laravel/pao replaces PHPUnit’s output with JSON when an AI agent runs the tests

Laravel 13’s skeleton includes laravel/pao (“agent-optimized output for PHP testing tools”). If an AI coding agent is detected from the environment, pao replaces PHPUnit’s progress and summary output with this line:

{"tool":"phpunit","result":"passed","tests":11,"passed":11,"assertions":27,"duration_ms":183}

It is triggered by environment variables such as AI_AGENT. Clear them and PHPUnit’s normal output returns. If a CI log parser that expects PHPUnit’s usual text gets this JSON instead after a Laravel upgrade, this is why.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.