Getting Started with PHPUnit

Download

We distribute a PHP Archive (PHAR) that contains everything you need in order to use PHPUnit. Simply download it from here, make it executable, and put it into your $PATH, for instance:

➜ wget https://phar.phpunit.de/phpunit.phar

➜ chmod +x phpunit.phar

➜ sudo mv phpunit.phar /usr/local/bin/phpunit

➜ phpunit --version
PHPUnit 4.2.0 by Sebastian Bergmann.

You can also immediately use the PHAR after you have downloaded it, of course:

➜ wget https://phar.phpunit.de/phpunit.phar

➜ php phpunit.phar --version
PHPUnit 4.2.0 by Sebastian Bergmann

Alternatively, you may use Composer to download and install PHPUnit as well as its dependencies. Please refer to the documentation for details on how to install PHPUnit using Composer.

Code

src/Money.php

<?php
class Money
{
    private $amount;

    public function __construct($amount)
    {
        $this->amount = $amount;
    }

    public function getAmount()
    {
        return $this->amount;
    }

    public function negate()
    {
        return new Money(-1 * $this->amount);
    }

    // ...
}

You can find the complete sourcecode of the Money class here.

Test Code

tests/MoneyTest.php

<?php
class MoneyTest extends PHPUnit_Framework_TestCase
{
    // ...

    public function testCanBeNegated()
    {
        // Arrange
        $a = new Money(1);

        // Act
        $b = $a->negate();

        // Assert
        $this->assertEquals(-1, $b->getAmount());
    }

    // ...
}



You can find the complete sourcecode of the MoneyTest class here.

Test Execution

➜ phpunit --bootstrap src/autoload.php tests/MoneyTest
PHPUnit 4.2.0 by Sebastian Bergmann.

....................

Time: 121 ms, Memory: 4.50Mb

OK (20 tests, 39 assertions)

Lets have a look at what the three parts of above's invokation mean:

  • phpunit invokes the PHPUnit command-line test runner. We assume that you have downloaded phpunit.phar (see above) and put it into your $PATH as phpunit.

  • --bootstrap src/autoload.php instructs the PHPUnit command-line test runner to include src/autoload.php before the test execution. Such a bootstrap script is commonly used to set up autoloading for the classes that are to be tested.

  • tests/MoneyTest instructs the PHPUnit command-line test runner to execute the tests of the MoneyTest class that is declared in tests/MoneyTest.php.

    Using tests instead of tests/MoneyTest would instruct the PHPUnit command-line test runner to execute all tests found declared in *Test.php sourcecode files in the tests directory.

Conclusion

You have learned how to write simple unit tests as well as how to download and run PHPUnit. For more details please have a look at the documentation.