Installing and Testing PHP Unit testing


Quick steps for implementing php unit testing on Ubuntu Apache. Unit test frame work is by https://phpunit.de/ by Sebastian Bergmann. All detailed documentation on that site.

Installation is easy by:

apt-get update
apt-get install phpunit

Test the version by:

phpunit --version

Create a class and some tests for the class. First 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);
    }
}

… and the test in 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());
    }

    // ...
}

Then just run it using following command line:

phpunit --bootstrap Money.php MoneyTest.php 

which should return:

PHPUnit 3.7.28 by Sebastian Bergmann.

.

Time: 82 ms, Memory: 2.75Mb

OK (1 test, 1 assertion)

Hey, it passed!