Chapter 13. Code-Coverage Analysis

You have learned how to use unit tests to test your code. But how do you test your tests? How do you find code that is not yet tested -- or, in other words, not yet covered by a test? How do you measure testing completeness? All these questions are answered by a practice called Code-Coverage Analysis. Code-Coverage Analysis gives you an insight into what parts of the production code are executed when the tests are run.

PHPUnit's Code-Coverage Analysis utilizes the statement coverage functionality provided by the Xdebug extension. An example of what statement coverage means is that if there is a method with 100 lines of code, and only 75 of these lines are actually executed when tests are being run, then the method is considered to have a code coverage of 75 percent.

Let us generate a code-coverage report for the BankAccount class from Example 12.3.

phpunit --report ./report BankAccountTest
PHPUnit 3.1.0 by Sebastian Bergmann.


Time: 00:00

OK (4 tests)

Generating report, this may take a moment.

The code-coverage report shows that we do not have any tests yet that call the setBalance(), depositMoney(), and withdrawMoney() methods with legal values.

Example 13.1 shows tests that need to be added to the BankAccountTest test-case class to completely cover the BankAccount class.

Example 13.1: Tests missing to achieve complete code-coverage

require_once 'PHPUnit/Framework.php';
require_once 'BankAccount.php';
class BankAccountTest extends PHPUnit_Framework_TestCase
    // ...
    public function testSetBalance()
        $this->assertEquals(1, $this->ba->getBalance());
    public function testDepositAndWidthdrawMoney()
        $this->assertEquals(1, $this->ba->getBalance());
        $this->assertEquals(0, $this->ba->getBalance());