Prev Next

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.0.0 by Sebastian Bergmann.

....

Time: 00:00

OK (4 tests)

Generating report, this may take a moment.

Figure 13.1 shows an excerpt from a Code Coverage report. Lines of code that were executed while running the tests are highlighted green, lines of code that are executable but were not executed are highlighted red, and "dead code" is highlighted orange. The number left to the actual line of code indicates how many tests cover that line.

Figure 13.1. Code Coverage for setBalance()

Code Coverage for setBalance()


The code-coverage report for our BankAccount example 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

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


Figure 13.2 shows the code coverage of the setBalance() method with the additional tests.

Figure 13.2. Code Coverage for setBalance() with additional tests

Code Coverage for setBalance() with additional tests


Prev Next