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.
Figure 9.1 shows
a code-coverage report for the BankAccount
class (from
Example 8.3)
in HTML format generated by the PHPUnit command-line test runner's
--coverage-html
switch. Executable code lines are
black; non-executable code lines are gray. Code lines that are actually
executed are highlighted.
The code-coverage report shows that we need to write tests that call
setBalance()
, depositMoney()
, and
withdrawMoney()
with legal values in order to achieve
complete code-coverage.
Example 9.1
shows tests that need to be added to the BankAccountTest
test-case class to completely cover the BankAccount
class.
Example 9.1: The BankAccount class, completeley covered by tests
<?php
require_once 'PHPUnit2/Framework/TestCase.php';
require_once 'BankAccount.php';
class BankAccountTest extends PHPUnit2_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());
}
}
?>
In Figure 9.2,
we see that the BankAccount
class is now completely
covered by tests.
In Chapter 12 you will learn how to use Phing to generate more detailed code-coverage reports.