コントローラおよび MVC アプリケーションのテスト
起動用の設定を済ませたら、テストの開始です。
テストの方法は PHPUnit テストスイートによるものとほぼ同じですが、
ちょっとした違いがいくつかあります。
まず、テストケースの dispatch()
メソッドを用いてテストの URL をディスパッチしなければなりません。
dispatch('/');
// ...
}
}
]]>
しかし、時にはこれ以外の情報 (GET 変数や POST 変数、
COOKIE 情報など) が必要になることもあります。
これらの情報をリクエストに含めることもできます。
request->setQuery(array(
'foo' => 'bar',
'bar' => 'baz',
));
// POST 変数を設定します
$this->request->setPost(array(
'baz' => 'bat',
'lame' => 'bogus',
));
// クッキーの値を指定します
$this->request->setCookie('user', 'matthew');
// あるいは複数の値を指定します
$this->request->setCookies(array(
'timestamp' => time(),
'host' => 'foobar',
));
// ヘッダを設定することもできます
$this->request->setHeader('X-Requested-With', 'XmlHttpRequest');
// リクエストメソッドを設定します
$this->request->setMethod('POST');
// ディスパッチします
$this->dispatch('/foo/bar');
// ...
}
}
]]>
リクエストが準備できたので、次はアサーションを作成してみましょう。
コントローラのテストと Redirector アクションヘルパー
Redirect アクションヘルパーは、gotoAndExit()
メソッドを使うときに exit()
ステートメントを発行し、このメソッドを使用するコントローラーに対するテストを全て停止させます。
アプリケーションのテスト容易性を考慮して、
リダイレクタではこのメソッドを使わないようにしましょう。
その性質上、リダイレクタアクションヘルパープラグインは
リダイレクトしたあと処理を終了します。
Because you cannot test parts of an application
that issue exit calls Zend_Test_PHPUnit_ControllerTestCase
automatically disables the exit part of the redirector as it can cause
test behavior to differ from the real application. To ensure your controllers can
be properly tested, please make use of the redirector when you need to redirect
the user to a different page:
_redirect(...);
} else if($anotherCondition == true) {
$this->_redirector->gotoSimple("foo");
return;
}
// do some stuff here
}
}
]]>
アプリケーションによっては、これだけでは不十分かもしれません。さらに
preDispatch() あるいは
postDispatch() といったロジックを実行するかもしれないからです。
現状の Zend Test では、これらをうまく処理することはできません。