How do I write unit tests in PHP?

How do I write unit tests in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

How do I write unit tests in PHP?

The confusion often stems from a lack of clear starting point rather than a lack of documentation. When you ask, "How do I test this?", the answer usually isn't a single magic command but a shift in how you structure your application logic. You cannot effectively test a monolith where functions have fifty dependencies and global state; you must isolate the behavior you want to verify.

Consider a simple function that calculates a discount on an order. If you define it as public static function calculateDiscount(Order $order), you are immediately facing problems. To write a unit test for this, you need to ensure that $order is fully mocked or that the function does not rely on external services like a database or an API call during execution.

Here is a concrete example of what that isolation looks like in practice:

// Application Logic
class DiscountCalculator
{
    public static function calculate(Order $order): float
    {
        return $order->getTotal() * 0.15;
    }
}

// The Unit Test
tests/Feature/DiscountCalculationTest.php

use Tests\TestCase;
use App\Models\Order;

class DiscountCalculationTest extends TestCase
{
    public function test_discount_is_calculated_correctly()
    {
        $order = new Order(100.00); // Mocked or factory-created object
        
        $this->assertEquals(15.00, DiscountCalculator::calculate($order));
    }
}

In this scenario, the test is trivial because the logic is pure. However, once you introduce a database query inside calculate(), the test becomes brittle. You would then need to use PHP's built-in mocking capabilities or a framework like PHPUnit's mockery integration to stub the repository call. The goal is that when your unit test runs, it executes in isolation, taking less than a second and failing only if the specific logic branch you are testing is broken.

Running these tests requires a setup step. You typically run php artisan test in a Laravel environment, or vendor/bin/phpunit in a vanilla PHP project. The framework handles the discovery of test files, but you must ensure your class names and namespaces align with the file structure.

One common pitfall developers encounter is testing too much logic at once. If your function calculates the discount, saves the order to the database, and sends an email notification, you have created an integration test masquerading as a unit test. You should split this into three distinct tests: one verifying the math, one verifying the repository save behavior, and one verifying the mailer logic. This separation allows you to pinpoint exactly where a failure occurs without debugging a chain of dependencies.

When dealing with complex objects, factories are essential. Instead of manually setting every property of an Order model in your test file, use a factory pattern or Laravel's built-in Model::factory() syntax. This keeps your test code DRY and readable.

If you find yourself struggling to isolate dependencies or set up the necessary mocks for your specific architecture, looking at how established frameworks handle this can provide a template. Resources like https://laravelcompany.com often offer deep dives into testing strategies within the Laravel ecosystem, specifically regarding how to structure tests for complex service classes without violating the Single Responsibility Principle.

Ultimately, writing unit tests is about confidence in refactoring. If you have a comprehensive suite of passing unit tests, you can modify internal logic with the assurance that any regression will cause a test failure immediately. Start small: pick one function, mock its dependencies, and write a test that covers both the success case and a failure case where possible.

Our network