1. Home
  2. Explore
  3. Computer Science
  4. Installing PHPUnit with Composer

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Installing PHPUnit with Composer

PHPUnit Setup and Unit Testing in PHP

Installing PHPUnit as a development dependency

PHPUnit is a testing framework for writing and running PHP tests. It is needed during development, but generally not on a production server, so it should be installed as a Composer development dependency:

composer require --dev phpunit/phpunit

The --dev flag records PHPUnit under require-dev in composer.json. Composer installs development dependencies for local work, while production installations can omit them. The installed version can be checked in composer.json or from the command line.


Configuring PHPUnit

A PHPUnit configuration file tells the test runner how to find tests and what files to load. A shared template is conventionally named phpunit.xml.dist; a developer may create a local phpunit.xml to override it. When both exist, PHPUnit uses phpunit.xml first and falls back to phpunit.xml.dist if the local file is absent.

A basic PHPUnit 10 configuration can include:

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

    <source>
        <include>
            <directory suffix=".php">src</directory>
        </include>
    </source>
</phpunit>

The main configuration elements are:

  • bootstrap: Loads a file before tests run. In this setup, Composer’s vendor/autoload.php makes project and dependency classes available through autoloading. A separate test bootstrap file is only needed if tests require additional initialization.

  • colors: Enables colored terminal output to make passing and failing tests easier to distinguish.

  • cacheDirectory: Specifies where PHPUnit stores its generated test cache.

  • testsuites: Defines groups of tests. The Unit suite searches the tests directory.

  • source: Identifies the project source directory and includes PHP files from src for source-related test reporting.

The XML schema reference must match the installed PHPUnit version. PHPUnit documentation also describes additional options, but the configuration above provides a practical starting point.


Organizing test files and namespaces

Tests are commonly stored in a plural tests directory, separate from application source files in src. The configured test-suite directory must match the actual directory name.

A test for a User entity might be placed at:

tests/Entity/UserTest.php

The test namespace conventionally follows the project’s namespace with a Tests segment, followed by the relevant subnamespace. The test imports the production class it exercises, such as the project’s Entity\User class.

Composer’s autoloader should be configured for the project’s production namespace. PHPUnit’s bootstrap loads that autoloader, so test files can use project classes without manually requiring each source file.


Writing a PHPUnit test class

A PHPUnit test class extends PHPUnit\Framework\TestCase. A typical entity test class is declared final, because test classes are generally not designed to be extended.

<?php

declare(strict_types=1);

namespace Project\Tests\Entity;

use PHPUnit\Framework\TestCase;
use Project\Entity\User;

final class UserTest extends TestCase
{
    private User $user;

    protected function setUp(): void
    {
        parent::setUp();
        $this->user = new User();
    }
}

Strict types are enabled with declare(strict_types=1);. This makes PHP enforce declared argument and return types strictly rather than automatically coercing certain values.

The setUp() method runs before each test method. It is useful for creating a fresh object or other shared test state. Calling parent::setUp() preserves any setup behavior provided by PHPUnit’s base test case.

The typed property $user records the entity used by the tests. Each test starts with a newly constructed User, helping keep tests independent.


Testing a sequential ID getter

A test method is typically public, begins with test, and declares void when it returns no value. Its name should communicate the behavior being tested.

public function testSequentialId(): void
{
    $this->user->setSequentialId(55);

    self::assertSame(55, $this->user->getSequentialId());
}

This test assigns an ID and checks that the getter returns the expected value. assertSame() compares both value and type, using strict equality in PHP. For example, an integer value of 55 does not match the string value "55".

A test passes when the actual value equals the expected value exactly. Changing the expected value to an incorrect one should make the test fail, demonstrating that the assertion detects a mismatch.


Testing a UUID getter

A UUID setter/getter test can use Ramsey UUID to generate a valid UUID value:

use Ramsey\Uuid\Uuid;

public function testUserUuid(): void
{
    $uuid = Uuid::uuid4()->toString();

    $this->user->setUserUuid($uuid);

    self::assertSame($uuid, $this->user->getUserUuid());
}

Uuid::uuid4() creates a version 4 UUID object. Calling toString() converts it to the string representation used by the entity. This matters because the UUID library returns an object, while the entity may store or expose a string.

The test checks that the value passed to the setter is the same value returned by the getter.


Testing entity unserialization

An entity’s unserialize() method can be tested by passing it an array of stored user data and verifying that the corresponding getters expose the expected values.

A representative input might contain:

  • id: a sequential numeric identifier

  • user_uuid: a UUID string

  • first_name and last_name: name values

  • email and phone: contact information

  • password: a test value

  • created_date: a date string in the format expected by the entity

The test can then assert each property:

public function testUnserialize(): void
{
    $expected = [
        'id' => 5,
        'user_uuid' => 'a-valid-uuid-string',
        'first_name' => 'Pierre',
        'last_name' => 'Surya',
        'email' => 'me@example.test',
        'phone' => '0000000000',
        'password' => 'test-password',
        'created_date' => 'a-date-in-the-expected-format',
    ];

    $this->user->unserialize($expected);

    self::assertSame($expected['id'], $this->user->getSequentialId());
    self::assertSame($expected['user_uuid'], $this->user->getUserUuid());
    self::assertSame($expected['first_name'], $this->user->getFirstName());
    self::assertSame($expected['last_name'], $this->user->getLastName());
    self::assertSame($expected['email'], $this->user->getEmail());
    self::assertSame($expected['phone'], $this->user->getPhone());
    self::assertSame($expected['password'], $this->user->getPassword());
    self::assertSame($expected['created_date'], $this->user->getCreationDate());
}

The keys and values should match the contract expected by the entity. In particular, the creation date should use the format the application stores and the entity expects. If an entity does not yet implement a field, such as a session token or last-session time, there is no getter behavior to test for that field yet.

Testing several getters this way verifies that unserialize() maps the supplied data to the correct entity properties. If a value in the expected array differs from what the entity returns, the relevant assertion fails.


Running tests

When PHPUnit is installed globally, the test suite can be run with:

phpunit

If it is installed only in the project, use the executable in Composer’s vendor directory:

vendor/bin/phpunit

A successful run reports the tests and assertions that passed. A failure identifies the relevant test and shows the difference between expected and actual values. This makes even a deliberately incorrect expected value a useful check that the test is actually detecting errors.

A single test can be selected with the --filter option:

vendor/bin/phpunit --filter 'UserTest::testUnserialize'

Filtering is useful while developing a particular test because it runs only tests whose names match the supplied pattern.


Ignoring generated files and excluding tests from packages

PHP projects often need to distinguish between files that should not be committed and files that should not be included in a distributable package.

.gitignore

.gitignore tells Git to ignore local files or directories that should not be tracked. Typical examples include PHPUnit’s generated cache directory and a local phpunit.xml override. The shared phpunit.xml.dist template is usually kept under version control.

The test suite itself should normally be committed: ignoring the tests directory would prevent the project’s tests from being shared with collaborators.

.gitattributes and export-ignore

.gitattributes can mark files or directories with export-ignore. This excludes them from Git-generated archives, such as source archives prepared for distribution, without removing them from the repository.

For a library package, tests, development-only PHPUnit configuration, and other files unnecessary to package users may be excluded from archives. These files can remain committed in Git while being omitted from the distributed archive.

PHPUnit’s generated cache

PHPUnit creates its cache directory automatically when tests run. Since it is generated local data, the cache is a suitable entry for .gitignore.


Practical test workflow

  1. Install PHPUnit with Composer as a development dependency.

  2. Configure PHPUnit to load Composer’s autoloader and search the project’s tests directory.

  3. Create a test class that extends TestCase; use setUp() to prepare fresh test data.

  4. Write focused tests for entity behavior, using assertSame() when both the value and type must match.

  5. Run the full suite, or filter for a specific test while working on it.

  6. Keep generated cache and local configuration out of Git, while committing the tests and shared configuration template.

A well-structured unit test checks observable behavior—such as whether a getter returns the value assigned by a setter—without requiring unrelated parts of the application to run.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent