simple_test のススメ
phpでテストscript書こうと思って、せっかくなんでちゃんと世間的に有名な書き方に慣れておこうと思った。
なので、まずはphpでよく使われるtest codeを探す
SimpleTest
なんかSimple Testが有名らしい。
symfonyのUnitTestにも使われているらしいし、CakePHPでも使ってる人いた。
今回のtest codeはシンプルだし、使いやすそうなこいつを使う事にする。
install
基本は、落として、解凍して、適当なdir置くだけ。
本家
SimpleTest - Unit Testing for PHP
落として
SimpleTest - Unit Testing for PHP
使い方
読み込みましょう。
require_once 'simpletest/unit_tester.php'; require_once 'simpletest/reporter.php';
// UnitTestCase を継承して // 適当にわかりやすいクラス名で class TestHoge extends UnitTestCase { // php のversionに合わせて、コンストラクタの呼び方は適当に変えて public function __construct() { $this->UnitTestCase(); } // test という文字列で始まるテストコードを書く public function testSample() { // ここにテストを書く } } $test = new TestHoge; $test->run(new TextReporter());
な感じで使う。
ある程度ひな形。
内部のメソッドは複数書いてOK。
なんか、test*****を勝手に探して、勝手に実行してくれる。
便利。
んで、テストコードの書き方だけど、
$this->assertTrue($hoge);
とか、
$this->assertEqual($first, $second);
とか、色々なメソッドがある。
全部書くと大変だから、ちょっとだけまとめると、
- assertTrue($x)
- Fail if $x is false : $xが偽でエラー
- assertFalse($x)
- Fail if $x is true : $xが真でエラー
- assertNull($x)
- Fail if $x is set : $xがNULLでエラー
- assertNotNull($x)
- Fail if $x not set : $xがNULLじゃなければエラー
- assertIsA($x, $t)
- Fail if $x is not the class or type $t : $xオブジェクトが$tタイプじゃなかったらエラー
- assertNotA($x, $t)
- Fail if $x is of the class or type $t : $xオブジェクトが$tタイプだったらエラー
- assertEqual($x, $y)
- Fail if $x == $y is false : $xと$yが等しくなければエラー
- assertNotEqual($x, $y)
- Fail if $x == $y is true : $xと$yが等しければエラー
他にもあるけど、あまり使わないかな。
原文だけのせておく。
assertWithinMargin($x, $y, $m) Fail if abs($x - $y) < $m is false assertOutsideMargin($x, $y, $m) Fail if abs($x - $y) < $m is true assertIdentical($x, $y) Fail if $x == $y is false or a type mismatch assertNotIdentical($x, $y) Fail if $x == $y is true and types match assertReference($x, $y) Fail unless $x and $y are the same variable assertClone($x, $y) Fail unless $x and $y are identical copies assertPattern($p, $x) Fail unless the regex $p matches $x assertNoPattern($p, $x) Fail if the regex $p matches $x expectError($x) Swallows any upcoming matching error assert($e) Fail on failed expectation object $e
ちなみにレポートの吐き出し方は、TEXTとHTMLがあるようで、
$test->run(new HtmlReporter());
こんなのも行ける。
ちなみに使った事ないので、どうなるかしらないw
きっと、HTML吐き出して、エラーとか見やすいんだと思う。