Programster's Blog

Tutorials focusing on Linux, programming, and open-source

PHPUnit - Get Started Writing Tests With Assertions

  • Unit tests should ideally cover all the possible paths in an application with one unit test covering one specific path in one function or method.
  • The tests for a class called Class should go into a class called ClassTest.
  • Test classes should inherits (most of the time) from PHPUnit_Framework_TestCase.
  • The tests are public methods that are named test*. Alternatively, you can use the @test annotation in a method's docblock to mark it as a test method.
  • Inside the test methods, assertion methods such as assertEquals() are used to assert that an actual value matches an expected value.

Below is an example test class:

<?php
class StackTest extends PHPUnit_Framework_TestCase
{
    public function testPushAndPop()
    {
        $stack = array();
        $this-&gt;assertEquals(0, count($stack));

        array_push($stack, 'foo');
        $this-&gt;assertEquals('foo', $stack[count($stack)-1]);
        $this-&gt;assertEquals(1, count($stack));

        $this-&gt;assertEquals('foo', array_pop($stack));
        $this-&gt;assertEquals(0, count($stack));
    }
}

Assertions

Here are a list of all the assertions that come with PHPunit.

Arrays

Booleans

Classes / Objects

Comparison

Files

JSON

Strings

XML

Mixed / Misc

Last updated: 1st May 2024
First published: 16th August 2018