モデルを使わないコンポーネントの単体テスト

このエントリーをはてなブックマークに追加
はてなブックマーク - モデルを使わないコンポーネントの単体テスト
Share on Facebook

CakePHP 1.3.2でコンポーネントを単体テストする場合、モデルの有無によって大幅に面倒くささが変わってきます。なぜならコンポーネントはモデルを直接操作できないので、間にコントローラを作成する必要があるからです。

公式マニュアルにある方法はモデルを使うケースのみで、しかもわかりづらいです (どのファイルのどのブロックに書いてるのかわからない)。今回はモデル無しのコンポーネントのテスト方法をメモしておきます。

やり方

以下のコンポーネント、「HigeComponent」をテストする場合を考えます。

// app/controllers/components/hige.php
<?php
class HigeComponent extends Object {
    function moja() {
        return "mojamoja";
    }
}
?>

テストケースは下記の通り、コンポーネントを読み込んで直接実行するだけです。

// app/tests/cases/components/hige.test.php
<?php
App::import("Component", "Hige");
    
class HigeComponentTestCase extends CakeTestCase {
    function setUp() {
        $this->component = new HigeComponent();
    }
    
    // テストケース
    function testMoja() {
        $result = $this->component->moja();
        $expected = "moja";
        
        $this->assertEqual($result, $expected);
    }
}
?>

あとは、下記の通りコマンドを打ち込めばOK。(cake.batにパスを通さずやってます)

cd c:\xampp\htdocs\cakephp\app
../cake/console/cake testsuite app case components/hige

出力結果


Welcome to CakePHP v1.3.2 Console
---------------------------------------------------------------
App : app
Path: c:\xampp\htdocs\cakephp\app
---------------------------------------------------------------
CakePHP Test Shell
---------------------------------------------------------------
Running app case components/hige
1/1 test cases complete: 1 passes.
Time taken by tests (in seconds): 0.016170024871826
Peak memory use: (in bytes): 11,534,288

参考

assertionは下記を参考に。

  1. ありがとーーーーーーーーーーーーーーーーーーーーーーーー! 僕も公式のでどこにどこをかけばいいのか・・・。 半日かかってはまってたんですけど、この記事で一発で理解できました。

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>