Unit testing is useful to test individual parts of the program, to check if they respect the specifications. Actually as any type of testing, can only point out bugs, but can’t prove that the program is correct.
Despite that, they are very useful during development, as TDD (Test Driven Development) suggests, it can be a good idea to write the test before the actual code. It clears up the specification of the method and may point out that we have to refine the specification a little before start coding, for instance about handling of special cases. When our code pass all the test the job is done, or at least done for that method.
PHP doesn’t have the awesome tools that come with Java, but in this respect there is a simpler implementation of Unit Testing that is still quite useful, called PHPUnit.
Installation
PHPUnit Manual describes installation in details, but actually on Ubuntu installation is much simpler. It’s enough to install package phpunit and the framework will be installed in /usr/share/php/PHPUnit.
Writing a test
Writing a test is as simple as defining a class, that by convention we call as the class we want to test with Test suffix. For example if we need to test a class named Customer, our unit test class will be called CustomerTest.
require_once "Customer.php";
require_once "PHPUnit/Framework.php"; //since /usr/share/php is in the path
class CustomerTest extends PHPUnit_Framework_Test {
private $customer;
//anything that should be set up before running the tests
public static function setUpBeforeClass() {
$this->customer = new Customer();
}
//a test method for myMethod()
public function testMyMethod() {
$result = $this->customer->myMethod();
$this->assertEquals(43, $result);
}
}
Running the tests
To run the test from the command line, is enough to type:
phpunit CustomerTest.php
This is the basics to start using tests, but there is much more information in the online manual.