PHPUnitManual:19.5

From 흡혈양파의 번역工房
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
19.5 PHPUnit_Framework_Test 구현

PHPUnit_Framework_Test 인터페이스의 기능은 한정되어 있기에 간단히 구현할 수 있습니다. PHPUnit_Framework_Test 를 구현하는 것은 PHPUnit_Framework_TestCase 를 구현하는 것보다 간단합니다. PHPUnit_Framework_Test 의 구현을 통해 data-driven 테스트 등을 실행할 수 있습니다.


CSV 파일의 값과 비교하는 data-driven 테스트의 예를 예19.5 "data-driven 테스트" 에 보입니다. 이 파일의 각 행은 foo;bar 와 같은 형식으로 구성되어 있고 (역주 : CSV 파일이 아닌데...), 첫번째 값이 기대값, 2번째 값이 실제값입니다.


예19.5 data-driven 테스트

<?php
class DataDrivenTest implements PHPUnit_Framework_Test
{
    private $lines;
 
    public function __construct($dataFile)
    {
        $this->lines = file($dataFile);
    }
 
    public function count()
    {
        return 1;
    }
 
    public function run(PHPUnit_Framework_TestResult $result = NULL)
    {
        if ($result === NULL) {
            $result = new PHPUnit_Framework_TestResult;
        }
 
        foreach ($this->lines as $line) {
            $result->startTest($this);
            PHP_Timer::start();
            $stopTime = NULL;
 
            list($expected, $actual) = explode(';', $line);
 
            try {
                PHPUnit_Framework_Assert::assertEquals(
                  trim($expected), trim($actual)
                );
            }
 
            catch (PHPUnit_Framework_AssertionFailedError $e) {
                $stopTime = PHP_Timer::stop();
                $result->addFailure($this, $e, $stopTime);
            }
 
            catch (Exception $e) {
                $stopTime = PHP_Timer::stop();
                $result->addError($this, $e, $stopTime);
            }
 
            if ($stopTime === NULL) {
                $stopTime = PHP_Timer::stop();
            }
 
            $result->endTest($this, $stopTime);
        }
 
        return $result;
    }
}
 
$test = new DataDrivenTest('data_file.csv');
$result = PHPUnit_TextUI_TestRunner::run($test);
?>
PHPUnit 3.7.0 by Sebastian Bergmann.

.F

Time: 0 seconds

There was 1 failure:

1) DataDrivenTest
Failed asserting that two strings are equal.
expected string <bar>
difference      <  x>
got string      <baz>
/home/sb/DataDrivenTest.php:32
/home/sb/DataDrivenTest.php:53

FAILURES!
Tests: 2, Failures: 1.


Notes