Приглашаем посетить
Чернышевский (chernyshevskiy.lit-info.ru)

Section 16-4.  Implement PHPUnit2_Framework_Test

Previous
Table of Contents
Next

16-4. Implement PHPUnit2_Framework_Test

The PHPUnit2_Framework_Test interface is narrow and easy to implement. You can write an implementation of PHPUnit2_ Framework_Test that is simpler than PHPUnit2_Framework_ TestCase and that runs data-driven tests, for instance.

Example 25 shows a data-driven test-case class that compares values from a file with Comma-Separated Values (CSV). Each line of such a file looks like foo;bar, where the first value is the one we expect and the second value is the actual one.

Example 25. A data-driven test
<?php
require_once 'PHPUnit2/Framework/Assert.php';
require_once 'PHPUnit2/Framework/Test.php';
require_once 'PHPUnit2/Framework/TestResult.php';

class DataDrivenTest implements PHPUnit2_Framework_Test { 
	const DATA_FILE = 'data.csv';

  public function __construct( ) {
		$this->lines = file(self::DATA_FILE);
	}

  public function countTestCases( ) {
		return sizeof($this->lines);
	}

	public function run($result = NULL) {    
		if ($result === NULL) { 
			$result = new PHPUnit2_Framework_TestResult; 
		}

		$result->startTest($this);

		foreach ($this->lines as $line) { 
			list($expected, $actual) = explode(';', $line);

			try {

				PHPUnit2_Framework_Assert::assertEquals( trim($expected), 
				trim($actual)); 
			}

			catch (PHPUnit2_Framework_ComparisonFailure $e) { 
				$result->addFailure($this, $e); 
			}

			catch (Exception $e) { 
				$result->addError($this, $e); 
			} 
		}
	
		$result->endTest($this);

		return $result;
	}
}

$test = new DataDrivenTest;
$result = $test->run( );

$failures = $result->failures( );
print $failures[0]->thrownException( )->toString( );
?>
expected: <foo> but was: <bar>


Previous
Table of Contents
Next