Chapter 7. Testing Exceptions and Performance Regressions

PHPUnit provides two extensions that aid in the writing of tests for exceptions and performance regressions to the standard base class for test classes, PHPUnit2_Framework_TestCase.

Exceptions

How do you test exceptions? You cannot assert directly that they are raised. Instead, you have to use PHP's exception handling facilities to write the test. The following example demonstrates testing exceptions:

	<?php
	require_once 'PHPUnit2/Framework/TestCase.php';

	class ExceptionTest extends PHPUnit2_Framework_TestCase {
    public function testException( ) {
      try {
        // … Code that is expected to raise an
				// Exception …
				$this->fail('No Exception has been raised.');
      }

      catch (Exception $expected) {
			}
    }
  }
  ?>

If the code that is expected to raise an exception does not raise an exception, the subsequent call to fail( ) (see Table 7, later in this book) will halt the test and signal a problem with the test. If the expected exception is raised, the catch block will be executed, and the test will continue executing.

Alternatively, you can extend your test class from PHPUnit2_ Extensions_ExceptionTestCase to test whether an exception is thrown inside the tested code. Example 7 shows how to subclass PHPUnit2_Extensions_ExceptionTestCase and use its setExpectedException( ) method to set the expected exception. If this expected exception is not thrown, the test will be counted as a failure.

Example 7. Using PHPUnit2_Extensions_ExceptionTestCase

<?php require_once ...

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.