PHPUnit Testing Tutorial: Write Your First PHP Unit Test (2026)

By Lyndon Bermoy

Updated on:

PHPUnit Testing Tutorial: Write Your First PHP Unit Test (2026)

Testing is the professional practice that separates code that works now from code you can confidently change later. PHPUnit is PHP’s standard unit testing framework — it is what Laravel uses internally, it is what most PHP packages use, and it is what employers expect PHP developers to know. This tutorial gets you from zero to writing real tests.

Why Write Tests?

Before the tutorial: the common objection is “I can just test manually.” Manual testing has a critical flaw — it does not scale. When your application has 50 functions across 20 files, manually verifying that a change to one function did not break the other 49 is impractical. PHPUnit runs all your tests in seconds and immediately tells you what broke.

Tests also serve as documentation — a test that describes expected behaviour is often clearer than a comment.

Step 1: Install PHPUnit

# Install as a development dependency (not in production):
composer require --dev phpunit/phpunit

# Verify installation:
vendor/bin/phpunit --version
# PHPUnit 11.x.x by Sebastian Bergmann and contributors.

Step 2: Configure PHPUnit

Create phpunit.xml in your project root:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
         testdox="true">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
        <testsuite name="Feature">
            <directory>tests/Feature</directory>
        </testsuite>
    </testsuites>
</phpunit>

Create the test directories:

mkdir -p tests/Unit tests/Feature

Step 3: Write Your First Test

Let’s test a simple PHP class. First, the class to test:

// src/Calculator.php
namespace App;

class Calculator {
    public function add(float $a, float $b): float {
        return $a + $b;
    }

    public function divide(float $a, float $b): float {
        if ($b === 0.0) {
            throw new \DivisionByZeroError('Cannot divide by zero.');
        }
        return $a / $b;
    }

    public function percentage(float $value, float $total): float {
        if ($total === 0.0) {
            return 0.0;
        }
        return round(($value / $total) * 100, 2);
    }
}

Now the test class:

// tests/Unit/CalculatorTest.php
namespace Tests\Unit;

use App\Calculator;
use PHPUnit\Framework\TestCase;

class CalculatorTest extends TestCase {

    private Calculator $calculator;

    protected function setUp(): void {
        $this->calculator = new Calculator();
    }

    public function test_add_two_positive_numbers(): void {
        $result = $this->calculator->add(5, 3);
        $this->assertEquals(8, $result);
    }

    public function test_add_negative_numbers(): void {
        $this->assertEquals(-2, $this->calculator->add(-5, 3));
        $this->assertEquals(-8, $this->calculator->add(-5, -3));
    }

    public function test_divide_returns_correct_result(): void {
        $this->assertEquals(4.0, $this->calculator->divide(12, 3));
        $this->assertEquals(2.5, $this->calculator->divide(5, 2));
    }

    public function test_divide_by_zero_throws_exception(): void {
        $this->expectException(\DivisionByZeroError::class);
        $this->expectExceptionMessage('Cannot divide by zero.');
        $this->calculator->divide(10, 0);
    }

    public function test_percentage_calculates_correctly(): void {
        $this->assertEquals(50.0, $this->calculator->percentage(50, 100));
        $this->assertEquals(33.33, $this->calculator->percentage(1, 3));
    }

    public function test_percentage_with_zero_total_returns_zero(): void {
        $this->assertEquals(0.0, $this->calculator->percentage(50, 0));
    }
}

Run the tests:

vendor/bin/phpunit tests/Unit/CalculatorTest.php

You should see green output indicating all tests pass.

READ ALSO:   How to Deploy a PHP Application to Hostinger: Step-by-Step Guide (2026)

Common PHPUnit Assertions

// Value equality:
$this->assertEquals(expected, actual);        // Loose equality
$this->assertSame(expected, actual);          // Strict equality (===)
$this->assertNotEquals(unexpected, actual);

// Boolean:
$this->assertTrue($value);
$this->assertFalse($value);

// Null:
$this->assertNull($value);
$this->assertNotNull($value);

// Arrays:
$this->assertCount(3, $array);
$this->assertContains('item', $array);
$this->assertArrayHasKey('key', $array);

// Strings:
$this->assertStringContainsString('substring', $string);
$this->assertStringStartsWith('prefix', $string);
$this->assertMatchesRegularExpression('/pattern/', $string);

// Exceptions:
$this->expectException(ExceptionClass::class);
$this->expectExceptionMessage('message text');
$this->expectExceptionCode(404);

// Types:
$this->assertInstanceOf(ClassName::class, $object);
$this->assertIsString($value);
$this->assertIsInt($value);
$this->assertIsArray($value);

Test Doubles: Mocks and Stubs

When testing a class that depends on other classes (database, API calls, email sending), you replace the dependencies with test doubles — controlled fakes that return predictable values without hitting real external systems.

// The class to test:
class UserService {
    public function __construct(private UserRepository $repository) {}

    public function getActiveUsers(): array {
        return array_filter(
            $this->repository->findAll(),
            fn($user) => $user['active'] === true
        );
    }
}

// The test with a mock:
class UserServiceTest extends TestCase {
    public function test_get_active_users_filters_inactive(): void {
        // Create a mock of UserRepository:
        $mockRepo = $this->createMock(UserRepository::class);

        // Define what findAll() returns when called:
        $mockRepo->method('findAll')->willReturn([
            ['name' => 'Alice', 'active' => true],
            ['name' => 'Bob',   'active' => false],
            ['name' => 'Carol', 'active' => true],
        ]);

        $service = new UserService($mockRepo);
        $result  = $service->getActiveUsers();

        $this->assertCount(2, $result);
        // Bob (inactive) is filtered out
    }
}

Testing Laravel Applications

Laravel includes PHPUnit pre-configured. Laravel’s test helpers make testing routes, forms, and authentication straightforward:

// tests/Feature/PostControllerTest.php
namespace Tests\Feature;

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

class PostControllerTest extends TestCase {
    use RefreshDatabase;  // Resets database between tests

    public function test_authenticated_user_can_create_post(): void {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->post('/posts', [
            'title'   => 'My Test Post',
            'content' => 'This is the post content.',
        ]);

        $response->assertRedirect('/posts');
        $this->assertDatabaseHas('posts', ['title' => 'My Test Post']);
    }

    public function test_unauthenticated_user_cannot_create_post(): void {
        $response = $this->post('/posts', [
            'title'   => 'Test',
            'content' => 'Content',
        ]);

        $response->assertRedirect('/login');
    }

    public function test_post_title_is_required(): void {
        $user = User::factory()->create();

        $response = $this->actingAs($user)->post('/posts', [
            'content' => 'Content without a title',
        ]);

        $response->assertSessionHasErrors('title');
    }
}

Running Tests

# Run all tests:
vendor/bin/phpunit

# Run specific test file:
vendor/bin/phpunit tests/Unit/CalculatorTest.php

# Run tests matching a name pattern:
vendor/bin/phpunit --filter test_add

# Run with coverage report (requires Xdebug):
vendor/bin/phpunit --coverage-html coverage/

# In Laravel:
php artisan test              # Runs all tests
php artisan test --filter PostController  # Specific tests

Frequently Asked Questions

What is the difference between unit tests and feature tests?

Unit tests test a single class or function in isolation — no database, no HTTP requests, no external services. Feature tests (also called integration tests) test the full application stack — HTTP request → controller → database → response. Both are valuable. Unit tests run faster and are easier to write; feature tests catch integration bugs that unit tests miss.

READ ALSO:   PHP Testing with Pest: Complete Guide for Beginners (2026)

Should I aim for 100% test coverage?

100% coverage is rarely the right goal — it leads to testing trivial getters and setters that have no business logic. Aim for high coverage on business-critical code (payment processing, authentication, data transformations) and accept lower coverage on framework boilerplate and simple CRUD operations. 70–80% coverage on meaningful code is more valuable than 100% coverage with trivial tests.

What is Pest PHP?

Pest is a PHPUnit wrapper with a more expressive, function-based syntax. It runs on top of PHPUnit and supports all PHPUnit features. Laravel 11 generates Pest tests by default. Both Pest and PHPUnit are valid professional choices — learn PHPUnit first (it is the foundation), then Pest is easy to adopt.

Conclusion

PHPUnit is not difficult to learn — the basics fit in one afternoon. The challenge is developing the discipline to write tests alongside your features rather than after them. Start with testing pure PHP functions (like the Calculator example), then move to testing service classes with mocked dependencies, then add Laravel feature tests for your routes and controllers. Each layer of tests gives you more confidence to refactor and extend your code without breaking existing functionality.

Next Step for Your Project Journey

Pick your next action to keep building: download complete source code, continue with practical tutorials, or explore more project systems.

Explore Source Code Continue Tutorials Final Year Projects

Leave a Comment