Chapter 10. 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[6] 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 overage of 75 percent.

Figure 1 shows a code-coverage report for the BankAccount class (from Example 12) 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 BankAccount class, not completely covered by tests

Figure 1-1. The BankAccount class, not completely covered by tests

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 14 shows tests that need to be added to ...

Get PHPUnit Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.