back to index

PHPUnit Basics

Common PHPUnit assertions and a simple test example.

published Jun 02, 2017 tags #php #testing

~/posts/phpunit-basic $ cat post.md

/ LANG EN / 中文
/ THEME / /

Unit testing is about exercising small components on their own so you don’t end up blindly debugging a huge codepath. On the PHP side the usual tool is PHPUnit.

Syntax

A handful of common assertions:

assertTrue(true);                                          # SUCCESSFUL
assertEquals('orz', 'oxz', 'The string is not equal');     # UNSUCCESSFUL
assertCount(1, array('Monday'));                           # SUCCESSFUL
assertContains('PHP', array('PHP', 'Java', 'Ruby'));       # SUCCESSFUL

A failing assertion aborts the rest of the test. Every assertion takes an optional trailing string used as the failure message.

An example

A small User / Event domain:

class User
{
    public $id;
    public $name;
    public $email;

    public function __construct($id, $name, $email)
    {
        $this->id = $id;
        $this->name = $name;
        $this->email = $email;
    }
}

class Event
{
    public $id;
    public $name;
    public $start_date;
    public $end_date;
    public $deadline;
    public $attendee_limit;
    public $attendees = array();

    public function __construct($id, $name, $start_date, $end_date, $deadline, $attendee_limit)
    {
        $this->id = $id;
        $this->name = $name;
        $this->start_date = $start_date;
        $this->end_date = $end_date;
        $this->deadline = $deadline;
        $this->attendee_limit = $attendee_limit;
    }

    public function reserve($user)
    {
        $this->attendees[$user->id] = $user;
    }

    public function getAttendeeNumber()
    {
        return sizeof($this->attendees);
    }
}

And the test:

require_once('../src/phpunitdemo/UserDemo.php');
require_once('../src/phpunitdemo/EventDemo.php');

class EventTest extends PHPUnit_Framework_TestCase
{
    public function testReserve()
    {
        $eventId = 1;
        $eventName = 'Event 1';
        $eventStartDate = '2014-12-24 18:00:00';
        $eventEndDate = '2014-12-24 20:00:00';
        $eventDeadline = '2014-12-23 23:59:59';
        $eventAttendeeLimit = 10;
        $event = new Event($eventId, $eventName, $eventStartDate,
            $eventEndDate, $eventDeadline, $eventAttendeeLimit);

        $userId = 1;
        $userName = 'User1';
        $userEmail = '[email protected]';
        $user = new User($userId, $userName, $userEmail);
        $event->reserve($user);

        $expectedNumber = 1;
        $this->assertEquals($expectedNumber, $event->getAttendeeNumber());
        $this->assertContains($user, $event->attendees);
    }
}

Rinse and repeat per class.

The base class above, PHPUnit_Framework_TestCase, is the pre-6.0 name. Modern code uses extends TestCase.

back to index