/ phpunit

PHPUnit 7 with PHP Archive (PHAR)

PHPUnit is a unit testing framework for the PHP programming language.
It is an instance of the xUnit architecture for unit testing frameworks that originated with SUnit and became popular with JUnit.
PHPUnit was created (2004) by Sebastian Bergmann and its development is hosted on GitHub

The goal of unit testing is to isolate each part of the program and show that the individual parts are correct.

Getting Started with PHPUnit 7

Note:This tutorial assumes that you use PHP 7.1 or PHP 7.2. You will learn how to write simple unit tests as well as how to download and run PHPUnit.

Installation

Download the PHP Archive (PHAR) that contains everything you need in order to use PHPUnit 7.
Simply download it from here and make it executable:

wget -O phpunit https://phar.phpunit.de/phpunit-7.phar
chmod +x phpunit
./phpunit --version
PHPUnit 7.0.0 by Sebastian Bergmann and contributors.

Testing our code

Create a file Email.php inside of src folder, with the code:

<?php
declare(strict_types=1);

final class Email
{
    private $email;

    private function __construct(string $email)
    {
        $this->ensureIsValidEmail($email);

        $this->email = $email;
    }

    public static function fromString(string $email): self
    {
        return new self($email);
    }

    public function __toString(): string
    {
        return $this->email;
    }

    private function ensureIsValidEmail(string $email): void
    {
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            throw new InvalidArgumentException(
                sprintf(
                    '"%s" is not a valid email address',
                    $email
                )
            );
        }
    }
}

Next, create a test file EmailTest.php inside of tests folder, with the code:

<?php
declare(strict_types=1);

use PHPUnit\Framework\TestCase;

final class EmailTest extends TestCase
{
    public function testCanBeCreatedFromValidEmailAddress(): void
    {
        $this->assertInstanceOf(
            Email::class,
            Email::fromString('user@example.com')
        );
    }

    public function testCannotBeCreatedFromInvalidEmailAddress(): void
    {
        $this->expectException(InvalidArgumentException::class);

        Email::fromString('invalid');
    }

    public function testCanBeUsedAsString(): void
    {
        $this->assertEquals(
            'user@example.com',
            Email::fromString('user@example.com')
        );
    }
}

The above assumes that we will have in src/autoload.inc.php , the script that sets up autoloading for the classes that are to be tested.
Such a script can be generated using a tool such as phpab, feel free to check phpab web for full details.

For our simple tutorial, we will use the following code, that assumes that we would like to test only one file Email.php.
Create the autoload.inc.php and add the code:

<?php
// @codingStandardsIgnoreFile
// @codeCoverageIgnoreStart
// this is an autogenerated file - do not edit
function autoload781c4547a8a27b6fa5d144d420cb36a4($class) {
    static $classes = null;
    if ($classes === null) {
        $classes = array(
            'email' => '/Email.php'
        );
    }
    $cn = strtolower($class);
    if (isset($classes[$cn])) {
        require dirname(__FILE__) . $classes[$cn];
    }
}
spl_autoload_register('autoload781c4547a8a27b6fa5d144d420cb36a4', true);
// @codeCoverageIgnoreEnd

File structure and filenames

The file structure and filenames should be:

./src/autoload.inc.php
./src/Email.php
./tests/EmailTest.php
./phpunit

Test Execution

The --bootstrap src/autoload.php instructs the PHPUnit command-line test runner to include src/autoload.php before the tests are run:
./phpunit --bootstrap src/autoload.php tests/EmailTest

or alternative output which is based on the idea that the name of a test can be used to document the behaviour that is verified by the test:
./phpunit --bootstrap src/autoload.inc.php --testdox tests

The output should be similar to:

/phpunit --bootstrap src/autoload.inc.php tests
PHPUnit 7.4.4 by Sebastian Bergmann and contributors.

...                                                                 3 / 3 (100%)

Time: 59 ms, Memory: 8.00MB

OK (3 tests, 3 assertions)

Extra info

How to start using PHP Autoload Builder, to generate an autoload require file.
The PHP AutoloadBuilder CLI tool phpab is a command line application to automate the process of generating an autoload require file with the option of creating static require lists as well as phar archives.

Manual install

Start to download last phar file release from Releases · theseer/Autoload · GitHub

(optional) Rename your phar file:
mv phpab-1.x.phar phpab

When using phpab it is necessary to recreate the autoload file every time a new class is created.
This usually also happens after pulling from a repo or when switchting branches. Using a git post-checkout hook placed in .git/hooks/post-update this can be automated for most cases.

Autoload file generation:
./phpab -c -o src/autoload.inc.php src

PHPUnit 7 with PHP Archive (PHAR)
Share this

Subscribe to NL Slack