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->assertEquals(0, count($stack));

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

        $this->assertEquals('foo', array_pop($stack));
        $this->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

Author

Programster

Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to Amazon.com and affiliated sites. More info.