PHPUnitManual:4.4

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.
4.4 PHP 에러의 테스트

PHP 에러의 테스트

초기값에서는, PHPUnit 은 테스트 실행 중에 발생한 PHP 의 에러나 경고, 주의 (notice) 를 예외로 변환합니다. 이런 예외를 사용하여 예제 4.11 "@expectedException 을 사용한, PHP 에러 발생 테스트" 와 같이 PHP 의 에러 발생을 테스트할 수 있습니다.


예제 4.11 @expectedException 을 사용한, PHP 에러 발생 테스트

<?php
class ExpectedErrorTest extends PHPUnit_Framework_TestCase
{
	/**
	 * @expectedException PHPUnit_Framework_Error
	 */
	public function testFailingInclude()
	{
		include 'not_existing_file.php';
	}
}
?>
PHPUnit 3.7.0 by Sebastian Bergmann.
.
Time: 0 seconds
OK (1 test, 1 assertion)phpunit ExpectedErrorTest
PHPUnit 3.7.0 by Sebastian Bergmann.
.
Time: 0 seconds
OK (1 test, 1 assertion)


PHPUnit_Framework_Error_Notice 및 PHPUnit_Framework_Error_Warning 은, 각각 PHP 의 주의와 경고에 대응합니다.


주의사항
예외를 테스트할 때는 가능한 한 한정적으로 테스트하여야 합니다. 매우 일반화된 클래스를 테스트한다면 예측하지 못 한 부작용을 일으킬 수 있습니다. 그렇기에 @expectedException 이나 setExpectedException() 을 사용하여 Exception 클래스를 테스트할 수 없도록 하였습니다.


에러를 일으키는 PHP 의 함수 (예를 들어 fopen 등) 에 의존하는 테스트를 실행할 때는, 테스트 안에서 에러를 억제할 수 있는 것을 이용할 수도 있습니다. 이렇게 함으로서 notice 때문에 PHPUnit_Framework_Error_Notice 를 발생시키지 않고 반환값만을 체크할 수 있습니다.


예제 4.12 PHP 의 에러가 발생하는 코드의 반환값 테스트

<?php
class ErrorSuppressionTest extends PHPUnit_Framework_TestCase
{
	public function testFileWriting() {
		$writer = new FileWriter;
		$this->assertFalse(@$writer->write('/is-not-writeable/file', 'stuff'));
	}
}
class FileWriter
{
	public function write($file, $content) {
		$file = fopen($file, 'w');
		if($file == false) {
			return false;
		}
		// ...
	}
}

?>
PHPUnit 3.7.0 by Sebastian Bergmann.
.
Time: 1 seconds, Memory: 5.25Mb
OK (1 test, 1 assertion)phpunit ErrorSuppressionTest
PHPUnit 3.7.0 by Sebastian Bergmann.
.
Time: 1 seconds, Memory: 5.25Mb
OK (1 test, 1 assertion)


에러를 억제하지 않는다면, 이 테스트는 실패하고 fopen(/is-not-writeable/file): failed to open stream: No such file or directory 가 발생합니다.


Notes