CakeRequest
を使用しているモックオブジェクトを変更する方法はありませんControllerTestCase::_testAction
。
唯一のチャンスは、サブクラス化して、そこにControllerTestCase
あるメソッドをコピーし、使用するパラメーターまたはオブジェクトを_testAction
渡すメソッドにパラメーターを追加することです。CakeRequest
以下の実装を参照してください。
テストケースでは、次のように使用します。
$testUrl = '/notes';
$request = $this->getMock('CakeRequest', array('_readInput'), array($testUrl));
$request->addParams(array('requested' => true));
$this->testAction('/notes', array(
'passed' => array('location'=>'location1'),
'return' => 'vars',
'request' => $request
));
MyControllerTestCase
class MyControllerTestCase() {
protected function _testAction($url = '', $options = array()) {
$this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
$options = array_merge(array(
'data' => array(),
'method' => 'POST',
'return' => 'result',
'request' => null
), $options);
$restore = array('get' => $_GET, 'post' => $_POST);
$_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
if (is_array($options['data'])) {
if (strtoupper($options['method']) == 'GET') {
$_GET = $options['data'];
$_POST = array();
} else {
$_POST = $options['data'];
$_GET = array();
}
}
if($options['request'] instanceof CakeRequest) {
$request = $options['request'];
} else {
$request = $this->getMock('CakeRequest', array('_readInput'), array($url));
}
if (is_string($options['data'])) {
$request->expects($this->any())
->method('_readInput')
->will($this->returnValue($options['data']));
}
$Dispatch = new ControllerTestDispatcher();
foreach (Router::$routes as $route) {
if ($route instanceof RedirectRoute) {
$route->response = $this->getMock('CakeResponse', array('send'));
}
}
$Dispatch->loadRoutes = $this->loadRoutes;
$Dispatch->parseParams(new CakeEvent('ControllerTestCase', $Dispatch, array('request' => $request)));
if (!isset($request->params['controller']) && Router::currentRoute()) {
$this->headers = Router::currentRoute()->response->header();
return;
}
if ($this->_dirtyController) {
$this->controller = null;
}
$plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
if ($this->controller === null && $this->autoMock) {
$this->generate($plugin . Inflector::camelize($request->params['controller']));
}
$params = array();
if ($options['return'] == 'result') {
$params['return'] = 1;
$params['bare'] = 1;
$params['requested'] = 1;
}
$Dispatch->testController = $this->controller;
$Dispatch->response = $this->getMock('CakeResponse', array('send'));
$this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
$this->controller = $Dispatch->testController;
$this->vars = $this->controller->viewVars;
$this->contents = $this->controller->response->body();
if (isset($this->controller->View)) {
$this->view = $this->controller->View->fetch('__view_no_layout__');
}
$this->_dirtyController = true;
$this->headers = $Dispatch->response->header();
$_GET = $restore['get'];
$_POST = $restore['post'];
return $this->{$options['return']};
}
}