16-3. Subclass PHPUnit2_Extensions_TestDecoratorYou can wrap test cases or test suites in a subclass of PHPUnit2_Extensions_TestDecorator, and use the Decorator design pattern to perform some actions before and after the test runs. PHPUnit ships with two concrete test decorators. The first, PHPUnit2_Extensions_RepeatedTest, is used to run a test repeatedly and only count it as a success if all iterations are successful. The second, PHPUnit2_Extensions_TestSetup, was discussed in the section "Fixtures," earlier in this book. Example 24 shows a cut-down version of the PHPUnit2_ Extensions_RepeatedTest test decorator that illustrates how to write your own test decorators. Example 24. The RepeatedTest Decorator<?php require_once 'PHPUnit2/Extensions/TestDecorator.php'; class PHPUnit2_Extensions_RepeatedTest extends PHPUnit2_Extensions_TestDecorator { private $timesRepeat = 1; public function __construct(PHPUnit2_Framework_Test $test, $timesRepeat = 1) { parent::__construct($test); if (is_integer($timesRepeat) && $timesRepeat >= 0) { $this->timesRepeat = $timesRepeat; } } public function countTestCases( ) { return $this->timesRepeat * $this->test-> countTestCases( ); } public function run($result = NULL) { if ($result === NULL) { $result = $this->createResult( ); } for ($i = 0; $i < $this->timesRepeat && !$result-> shouldStop( ); $i++) { $this->test->run($result); } return $result; } } ?> |