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
class from Example 12.3.
phpunit --report ./report BankAccountTestPHPUnit 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.
The code-coverage report for our
shows that we do not have any tests yet that call the
withdrawMoney() methods with legal values.
shows tests that need to be added to the
test-case class to completely cover the
Example 13.1: Tests missing to achieve complete code-coverage
class BankAccountTest extends PHPUnit_Framework_TestCase
public function testSetBalance()
public function testDepositAndWidthdrawMoney()
Figure 13.2 shows
the code coverage of the
setBalance() method with the