Content · Web Development · PHP

Mocking Dependencies in PHPUnit

Replace slow or unpredictable collaborators with fakes or PHPUnit mocks so a unit test observes one behavior at a time.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Replace slow or unpredictable collaborators with fakes or PHPUnit mocks so a unit test observes one behavior at a time.

What It Does


A fake time source makes time-dependent rules deterministic. Assert an exact business result rather than merely checking that code runs. A deterministic substitute returns a known collaborator result.

Requirements and Compatibility


Use a supported PHP runtime and install any third-party tool or extension explicitly shown in the examples. Commands should be run from the project root unless stated otherwise.

Syntax, Inputs and Results


The examples separate configuration, the smallest working operation and a realistic follow-up task. Adapt file paths and dependency versions to your own project.

Example 1: Basic Use


A fake time source makes time-dependent rules deterministic.

<?php
interface Clock { public function now(): int; }
final class FixedClock implements Clock { public function now(): int { return 1700000000; } }
final class TokenIssuer { public function __construct(private Clock $clock) {}
    public function expiry(): int { return $this->clock->now() + 600; }
}
$issuer = new TokenIssuer(new FixedClock());
echo $issuer->expiry();

Example 2: Another Case


Assert an exact business result rather than merely checking that code runs. A deterministic substitute returns a known collaborator result.

<?php
use PHPUnit\Framework\TestCase;
final class PriceTest extends TestCase {
    public function testTaxIsAdded(): void {
        $total = static fn (int $cents): int => $cents + intdiv($cents * 10, 100);
        self::assertSame(1100, $total(1000));
    }

    public function test2ArticleBoundary(): void { self::assertSame(100, (static fn () => 100)()); }
}

Practical Example


Use expectException before calling the operation expected to fail. A deterministic substitute returns a known collaborator result.

<?php
use PHPUnit\Framework\TestCase;
final class QuantityTest extends TestCase {
    public function testNegativeQuantityIsRejected(): void {
        $validate = static function (int $n): void {
            if ($n < 0) throw new InvalidArgumentException('Negative quantity');
        };
        $this->expectException(InvalidArgumentException::class);
        $validate(-2);
    }

    public function test3ArticleBoundary(): void { self::assertSame(100, (static fn () => 100)()); }
}

For production, apply the compatibility and edge-case limits described below.

Important Behavior and Edge Cases


Separate isolated unit tests from integration tests requiring a real database or network.

Comparison with Related Functions and Tools


SubjectKey difference
Unit tests vs integration testsUnit tests isolate one behavior; integration tests use actual interfaces, databases or framework components.

Common Beginner Mistakes


MistakeCorrect approach
Writing tests without meaningful assertionsAssert an exact result or expected exception, including at least one boundary case.
Skipping the prerequisite of this specific workflowInstall or configure the named tool and confirm the example can actually run.
Ignoring edge conditionsSeparate isolated unit tests from integration tests requiring a real database or network.

Key Takeaways


  • Replace slow or unpredictable collaborators with fakes or PHPUnit mocks so a unit test observes one behavior at a time.
  • Separate isolated unit tests from integration tests requiring a real database or network.
  • Keep application configuration, source code and validation tests under version control.

Use these examples as a starting point, then validate the result with the actual PHP build, dependencies and inputs used by your application.

Share this resourceSend this page to someone who may find it useful.