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

By Lyndon Bermoy

Updated on:

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

Pest is a PHP testing framework that provides a more expressive, function-based syntax on top of PHPUnit. Instead of classes and methods, you write it('does something', fn() => ...) and use a chainable expectation API. Laravel 11 generates Pest tests by default. This guide covers everything from installing Pest to writing real tests for PHP and Laravel applications.

Pest vs PHPUnit: Key Differences

Feature PHPUnit Pest
Test syntax Class + method Function + closure
Assertions $this->assertEquals() expect($val)->toBe()
Runs on PHPUnit Yes (itself) Yes (wrapper)
Coverage Xdebug / PCOV Same
Laravel default Laravel 10 and earlier Laravel 11
Learning curve Moderate Lower

Step 1: Install Pest

composer require pestphp/pest --dev

# For Laravel:
composer require pestphp/pest-plugin-laravel --dev
php artisan pest:install

# Verify:
vendor/bin/pest --version

Step 2: Write Your First Pest Test

// tests/Unit/CalculatorTest.php
use App\Calculator;

beforeEach(function () {
    $this->calc = new Calculator();
});

it('adds two numbers correctly', function () {
    expect($this->calc->add(5, 3))->toBe(8);
});

it('divides correctly', function () {
    expect($this->calc->divide(10, 2))->toBe(5.0);
});

it('throws on division by zero', function () {
    expect(fn() => $this->calc->divide(10, 0))
        ->toThrow(DivisionByZeroError::class, 'Cannot divide by zero');
});

test('percentage works with standard values', function () {
    expect($this->calc->percentage(50, 100))->toBe(50.0);
    expect($this->calc->percentage(1, 3))->toBe(33.33);
});

Pest Expectations API

// Equality:
expect($value)->toBe(5);            // Strict (===)
expect($value)->toEqual(5);         // Loose (==)
expect($value)->not->toBe(10);

// Truthiness:
expect($value)->toBeTrue();
expect($value)->toBeFalsy();        // false, 0, '', null, []
expect($value)->toBeNull();

// Arrays:
expect($array)->toHaveCount(3);
expect($array)->toContain('item');
expect($array)->toHaveKey('name');
expect($array)->toMatchArray(['name' => 'Lyndon', 'role' => 'admin']);

// Strings:
expect($string)->toContain('hello');
expect($string)->toStartWith('PHP');
expect($string)->toEndWith('.php');
expect($string)->toMatch('/^\d{4}-\d{2}$/');

// Numbers:
expect($number)->toBeGreaterThan(0);
expect($number)->toBeLessThanOrEqual(100);
expect($number)->toBeBetween(1, 10);

// Types:
expect($object)->toBeInstanceOf(User::class);
expect($value)->toBeString();
expect($value)->toBeInt();
expect($value)->toBeArray();

// Exceptions:
expect(fn() => riskyFunction())->toThrow(RuntimeException::class);
expect(fn() => riskyFunction())->toThrow(RuntimeException::class, 'specific message');

Data Providers (Datasets)

// Test multiple values with datasets:
it('validates email addresses', function (string $email, bool $valid) {
    expect(validate_email($email))->toBe($valid);
})->with([
    ['valid@example.com',   true],
    ['also.valid@test.org', true],
    ['not-an-email',        false],
    ['@nodomain.com',       false],
    ['missing@.com',        false],
]);

// Named datasets:
dataset('valid_passwords', [
    'strong password'  => ['Abc123!@#'],
    'passphrase'       => ['correct-horse-battery-staple'],
]);

it('accepts valid passwords', function (string $password) {
    expect(validate_password($password))->toBeTrue();
})->with('valid_passwords');

Testing Laravel with Pest

// tests/Feature/AuthTest.php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('allows authenticated users to view dashboard', function () {
    $user = User::factory()->create();

    $this->actingAs($user)
        ->get('/dashboard')
        ->assertOk()
        ->assertSee('Welcome');
});

it('redirects unauthenticated users to login', function () {
    $this->get('/dashboard')
        ->assertRedirect('/login');
});

it('creates a user via registration form', function () {
    $this->post('/register', [
        'name'                  => 'Lyndon',
        'email'                 => 'lyndon@example.com',
        'password'              => 'password',
        'password_confirmation' => 'password',
    ])->assertRedirect('/dashboard');

    $this->assertDatabaseHas('users', ['email' => 'lyndon@example.com']);
});

it('validates required fields on registration', function () {
    $this->post('/register', [])->assertSessionHasErrors(['name', 'email', 'password']);
});

Mocking with Pest

use Mockery;

it('sends email after user registers', function () {
    $mailer = Mockery::mock(MailerInterface::class);
    $mailer->shouldReceive('sendWelcome')->once()->with(Mockery::type(User::class));

    $service = new UserService($mailer);
    $service->register(['name' => 'Lyndon', 'email' => 'lyndon@example.com']);
});

// In Laravel — fake facades:
it('dispatches welcome job', function () {
    Queue::fake();

    $this->post('/register', validRegistrationData());

    Queue::assertPushed(SendWelcomeEmail::class, function ($job) {
        return $job->user->email === 'lyndon@example.com';
    });
});

Running Pest Tests

# Run all tests:
vendor/bin/pest

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

# Filter by test name:
vendor/bin/pest --filter "adds two numbers"

# With coverage (requires Xdebug or PCOV):
vendor/bin/pest --coverage --min=80

# Parallel execution (faster on multi-core machines):
vendor/bin/pest --parallel

# In Laravel:
php artisan test
php artisan test --parallel

Frequently Asked Questions

Should I use Pest or PHPUnit for a new Laravel project?

Pest is the Laravel 11 default and is the forward-looking choice for new Laravel projects. Its syntax is cleaner and the developer experience is better. PHPUnit skills transfer directly since Pest runs on top of it. If your team already knows PHPUnit well, staying with PHPUnit is perfectly valid — both produce the same results.

READ ALSO:   How To Earn Money From Clickbank. Easy Ways To Earn From Click Bank

Can I mix Pest and PHPUnit tests?

Yes. Pest runs PHPUnit test classes alongside Pest test files. You can migrate incrementally — new tests written in Pest style, existing PHPUnit tests left as-is.

Conclusion

Pest makes PHP testing more approachable with its expressive expectation API and function-based test syntax. The learning curve from zero to writing useful tests is shorter than PHPUnit’s class-based approach. For new Laravel projects (11+), Pest is the default and the recommended choice. The patterns here — datasets, mocking, RefreshDatabase, fake facades — cover the tests you will write most often in professional Laravel development.

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