PHPUnitAdvertisement概要 - PHPUnitとは
phpの単体テストフレームワーク。JavaでデファクトスタンダードとなっているJUnitをベースに構築されている。
PHPのプログラムに対する単体テストプログラムを同じくPHPで記述し、何度も再帰的に実行することができるようになる。 入手テストコードの作成から実行までの流れ
1.テスト対象のクラス(Apple.php)
<?php
class Apple{
var $name = null;
function setName($name){
$this->name = $name;
}
function getName(){
return $this->name;
}
}
?>
2.テストコードの記述(AppleTest.php)
<?php
require_once "PHPUnit.php";
require_once "Apple.php";
class AppleTest extends PHPUnit_TestCase
{
function AppleTest($name)
{
$this->PHPUnit_TestCase($name);
}
function testInit() {
$apple = new Apple();
$this->assertEquals(null, $apple->getName());
}
function testAccesser() {
$apple = new Apple();
$apple->setName("おうりん");
$this->assertEquals("おうりん", $apple->getName());
}
}
?>
3.テスト実行コードの作成(TestRunner.php)
<?php
require_once "PHPUnit.php";
require_once "AppleTest.php";
$suite = new PHPUnit_TestSuite("AppleTest");
$result = PHPUnit::run($suite);
print($result->toHTML());
?>
4.実行 ブラウザからTestRunner.phpへアクセスする。 テスト成功 ![]() 図1:テスト成功 テスト失敗 ![]() 図2:テスト失敗 スケルトンの作成
PHPUnitでは、定義済みのクラスからテストクラスのスケルトン(枠組み)を自動生成する機能が用意されている。PHPUnitに含まれているSkeleton.phpを利用する。
スケルトン作成(CreateAppleTest.php)
<?php
require_once "PHPUnit/Skeleton.php";
$skeleton = new PHPUnit_Skeleton("Apple", "Apple.php");
$skeleton->createTestClass();
$skeleton->writeTestClass();
?>
ブラウザからアクセスすると、Apple.phpから生成されたスケルトンが同じディレクトリに生成される。AppleTest.php <?php /** * PHPUnit test case for Apple * * The method skeletons below need to be filled in with * real data so that the tests will run correctly. Replace * all EXPECTED_VAL and PARAM strings with real data. * * Created with PHPUnit_Skeleton on 2006-05-20 */ require_once 'PHPUnit.php'; class AppleTest extends PHPUnit_TestCase { var $Apple; function AppleTest($name) { $this->PHPUnit_TestCase($name); } function setUp() { require_once 'Apple.php'; $this->Apple =& new Apple(PARAM); } function tearDown() { unset($this->Apple); } function testsetname() { $result = $this->Apple->setname(PARAM); $expected = EXPECTED_VAL; $this->assertEquals($expected, $result); } function testgetname() { $result = $this->Apple->getname(PARAM); $expected = EXPECTED_VAL; $this->assertEquals($expected, $result); } } // Running the test. $suite = new PHPUnit_TestSuite('AppleTest'); $result = PHPUnit::run($suite); echo $result->toString(); ?> Advertisement |
ショートカット・634・634ブログ ・このカテゴリのトップページに戻る ・Incubator(Pukiwiki) ・634ラボ UIコレクションギャラリー ZO-3ジェネレーター サイト検索Y!ログール |