Приглашаем посетить
Толстой А.Н. (tolstoy-a-n.lit-info.ru)

Chapter 10.  Code-Coverage Analysis

Previous
Table of Contents
Next

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 testedor, 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.

[6] http://www.xdebug.org/

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.

Chapter 10.  Code-Coverage Analysis

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 the BankAccountTest test-case class to completely cover the BankAccount class.

Example 14. The BankAccount class, 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 2, we see that the BankAccount class is now covered completely by tests.

In the "PHPUnit and Phing" section, later in this book, you will learn how to use Phing to generate more detailed code-coverage reports.


Previous
Table of Contents
Next