せかいや

いまいるここを、おもしろく http://sekai-in-the-box.appspot.com/

PHPUnit 使えるようになるまで編

インストールに成功するも、実行時エラー

ClassLoaderTest.php

<?php
require_once 'PHPUnit/Framework.php';
require_once 'core/ClassLoader.php';

class ClassLoaderTest extends PHPUnit_Framework_TestCase{}


■エラー1

php C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php

Call to undefined method PHP_CodeCoverage_Filter::getInstance() in C:\xampp\php\PEAR\PHPUnit\Framework.php on line 46
325712 1. {main}() C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php:0
328504 2. require_once('C:\xampp\php\PEAR\PHPUnit\Framework.php') C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php:2

■解決
PHPUnitのVerUpに伴い Framework.php ⇒ Autoload.phpを使用するよう。
書き換えてみるも再度エラー


■エラー2

Fatal error: require_once(): Failed opening required 'core/ClassLoader.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php on line 3
Call Stack:
0.0007 325712 1. {main}() C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php:0

確かにそのinclude_pathを見に行ってもClassLoader.phpは存在していない。require_onceのパス指定はどう書けばいいのか。


■解決
現在のファイルの場所をdirname関数で教えてあげればOK

ClassLoaderTest.php

<?php
require_once 'PHPUnit/Autoload.php';
require_once dirname(__FILE__). '/../../core/ClassLoader.php';

class ClassLoaderTest extends PHPUnit_Framework_TestCase{}

■成功!

C:\xampp\php>php C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php
C:\xampp\php>

■テスト実行方法

C:\xampp\php>phpunit C:\xampp\htdocs\application\tests\core\ClassLoaderTest.php

■テストコード

<?php
require_once 'PHPUnit/Autoload.php';
require_once dirname(__FILE__). '/../../core/ClassLoader.php';

class ClassLoaderTest extends PHPUnit_Framework_TestCase
{
	public function setUp()
	{
	    $this->classLoader = new ClassLoader;
	}
	
	public function test_registerDir()
	{
		$dir ="test";
		$this->classLoader->registerDir($dir);
		$result = (array)$this->classLoader;
		$this->assertEquals("test", $result["\0*\0dirs"][0]);
	}	
}


■実行結果

ReflectionException: Method suite does not exist in C:\xampp\php\PEAR\PHPUnit\Runner\BaseTestRunner.php
Call Stack:
0.0006 327648 1. {main}() C:\xampp\php\phpunit:0
0.0146 688752 2. PHPUnit_TextUI_Command::main(???) C:\xampp\php\phpunit:46
0.0146 689168 3. PHPUnit_TextUI_Command->run(array(2), bool) C:\xampp\php\PEAR\PHPUnit\TextUI\
0.0235 1050680 4. PHPUnit_Runner_BaseTestRunner->getTest(string(54), string(58), array(2)) C:\x
0.0472 2236288 5. ReflectionClass->getMethod(string(5)) C:\xampp\php\PEAR\PHPUnit\Runner\BaseTe
PHPUnit 3.7.22 by Sebastian Bergmann.
Time: 0 seconds, Memory: 3.50Mb
OK (1 test, 1 assertion)

↓テスト結果に出てくるReflectionExceptionはxdebug が有効になっていたら発生するみたい(※1)。無害そうなのでこのまま放置。

ReflectionException: Method suite does not exist in C:\xampp\php\PEAR\PHPUnit\Runner\BaseTestRunner.php

※1
http://stackoverflow.com/questions/8305417/phpunit-reflectionexception-method-suite-does-not-exist