PHPUnit is the most famous testing framework of xUnit family, with more than 10 years of experience among PHP applications. This framework is based upon the so-called Unit Testing concept, i.e. the test of single code units.

The Framework can be installed via Composer, allowing to use the autoloader feature of this component: so the tasks of framework and code loading under Test environment, are simplified.

{
    "config": {
        "bin-dir": "bin"
    },
    "require-dev": {
        "phpunit/phpunit": "4.*"
    },
    "autoload": {
        "psr-0": {"": "src"}
    }
}

By way of simple example, let's assume to have defined a class executing the sum of two numbers. Our goal is to test the code for executing sums under various scenarios: summing positive or negative numbers, cases where the input are not numeric etc. The test framework will allow to check the sum method, by validating the condition that the result is the one expected, after providing some assertions about the expected result type.

<?php
//src/Sum.php
class Sum
{
    public function add($in1, $in2)
    {
        return $in1 + $in2;
    }
}

The Sum object test is obtained via a definition to extend an object of type “PHPUnit_Framework_TestCase”. By default, all the Test objects shall have a name terminating with the Test string, e.g.: “SumTest”.

<?php
//tests/SumTest.php
class SumTest extends PHPUnit_Framework_TestCase
{
    private $sut;

    public function setUp()
    {
        $this->sut = new Sum();
    }

    public function testSumPositiveNumbers()
    {
        $this->assertEquals(2, $this->sut->add(1, 1));
    }

    public function testSumOneNegativeNumber()
    {
        $this->assertEquals(0, $this->sut->add(1, -1));
    }

    //...
}

Each Test method, used to verify our code unit, shall have a name starting with the keyword "test", e.g.: “testPositiveNumbers” according to our example. As you can see, you can validate the results via "assert" methods, provided by the Framework Test of PHPunit.

Now, you have only to run your test, specifying to PHPUnit tool the folder containing all the Test definitions.

bin/phpunit tests/

The framework will pass through all the folders belonging to the “tests” Path, to check our source code. In particular, we defined 1 TestCase containing 2 Tests: so, in case of successful check, the check result will be

PHPUnit 4.1.0 by Sebastian Bergmann.

..

Time: 26 ms, Memory: 3.00Mb

OK (2 tests, 2 assertions)

Comments

comments powered by Disqus

cloudparty

Follow Us