7-1. ExceptionsHow 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 'PHPUnit2/Extensions/ExceptionTestCase.php'; class ExceptionTest extends PHPUnit2_Extensions_ ExceptionTestCase { public function testException( ) { $this->setExpectedException('Exception'); } } ?> phpunit ExceptionTest PHPUnit 2.3.0 by Sebastian Bergmann. F Time: 0.006798 There was 1 failure: 1) testException(ExceptionTest) Expected exception Exception FAILURES!!! Tests run: 1, Failures: 1, Errors: 0, Incomplete Tests: 0. Table 1 shows the external protocol implemented by PHPUnit2_Extensions_ExceptionTestCase.
|