Topics Testing PHPUnit Setup & Configuration
intermediate 14 min read

PHPUnit Setup & Configuration

PHPUnit configuration, test suites, environment setup, and Laravel 13 testing improvements.

PHPUnit in Laravel

Laravel uses PHPUnit 12 with Laravel 13. Tests are in the tests/ directory.

// phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
colors="true"
bootstrap="vendor/autoload.php">
<testsuites>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
</testsuites>
<php>
<env name="APP_ENV" value="testing"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
</php>
</phpunit>

Creating Tests

// php artisan make:test UserTest
// php artisan make:test UserServiceTest --unit

namespace Tests\Feature;

use Tests\TestCase;

class UserTest extends TestCase
{
public function test_guests_cannot_access_dashboard(): void
{
$response = $this->get("/dashboard");
$response->assertRedirect("/login");
}

public function test_authenticated_user_can_view_dashboard(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)->get("/dashboard");
$response->assertStatus(200);
$response->assertSee("Welcome");
}
}

Running Tests

// php artisan test --compact
// php artisan test --compact tests/Feature/UserTest.php
// php artisan test --compact --filter=test_guests_cannot

Examples

<?php
namespace Tests\Unit;

use PHPUnit\Framework\Attributes\Test;
use Tests\TestCase;

class MathTest extends TestCase
{
    #[Test]
    public function addition_works(): void
    {
        \$result = 2 + 2;
        \$this->assertEquals(4, \$result);
    }
}

Your Notes

Sign in to take notes for this lesson.

Quiz

Testing Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.