CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.4 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.4
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • CakeTestCase
  • CakeTestLoader
  • CakeTestRunner
  • CakeTestSuite
  • CakeTestSuiteCommand
  • CakeTestSuiteDispatcher
  • ControllerTestCase
  • ControllerTestDispatcher
  • InterceptContentHelper
  1: <?php
  2: /**
  3:  * ControllerTestCase file
  4:  *
  5:  * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
  6:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7:  *
  8:  * Licensed under The MIT License
  9:  * For full copyright and license information, please see the LICENSE.txt
 10:  * Redistributions of files must retain the above copyright notice
 11:  *
 12:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 13:  * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
 14:  * @package       Cake.TestSuite
 15:  * @since         CakePHP(tm) v 2.0
 16:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 17:  */
 18: 
 19: App::uses('Dispatcher', 'Routing');
 20: App::uses('CakeTestCase', 'TestSuite');
 21: App::uses('Router', 'Routing');
 22: App::uses('CakeRequest', 'Network');
 23: App::uses('CakeResponse', 'Network');
 24: App::uses('Helper', 'View');
 25: App::uses('CakeEvent', 'Event');
 26: 
 27: /**
 28:  * ControllerTestDispatcher class
 29:  *
 30:  * @package       Cake.TestSuite
 31:  */
 32: class ControllerTestDispatcher extends Dispatcher {
 33: 
 34: /**
 35:  * The controller to use in the dispatch process
 36:  *
 37:  * @var Controller
 38:  */
 39:     public $testController = null;
 40: 
 41: /**
 42:  * Use custom routes during tests
 43:  *
 44:  * @var boolean
 45:  */
 46:     public $loadRoutes = true;
 47: 
 48: /**
 49:  * Returns the test controller
 50:  *
 51:  * @return Controller
 52:  */
 53:     protected function _getController($request, $response) {
 54:         if ($this->testController === null) {
 55:             $this->testController = parent::_getController($request, $response);
 56:         }
 57:         $this->testController->helpers = array_merge(array('InterceptContent'), $this->testController->helpers);
 58:         $this->testController->setRequest($request);
 59:         $this->testController->response = $this->response;
 60:         foreach ($this->testController->Components->loaded() as $component) {
 61:             $object = $this->testController->Components->{$component};
 62:             if (isset($object->response)) {
 63:                 $object->response = $response;
 64:             }
 65:             if (isset($object->request)) {
 66:                 $object->request = $request;
 67:             }
 68:         }
 69:         return $this->testController;
 70:     }
 71: 
 72: /**
 73:  * Loads routes and resets if the test case dictates it should
 74:  *
 75:  * @return void
 76:  */
 77:     protected function _loadRoutes() {
 78:         parent::_loadRoutes();
 79:         if (!$this->loadRoutes) {
 80:             Router::reload();
 81:         }
 82:     }
 83: 
 84: }
 85: 
 86: /**
 87:  * InterceptContentHelper class
 88:  *
 89:  * @package       Cake.TestSuite
 90:  */
 91: class InterceptContentHelper extends Helper {
 92: 
 93: /**
 94:  * Intercepts and stores the contents of the view before the layout is rendered
 95:  *
 96:  * @param string $viewFile The view file
 97:  * @return void
 98:  */
 99:     public function afterRender($viewFile) {
100:         $this->_View->assign('__view_no_layout__', $this->_View->fetch('content'));
101:         $this->_View->Helpers->unload('InterceptContent');
102:     }
103: 
104: }
105: 
106: /**
107:  * ControllerTestCase class
108:  *
109:  * @package       Cake.TestSuite
110:  */
111: abstract class ControllerTestCase extends CakeTestCase {
112: 
113: /**
114:  * The controller to test in testAction
115:  *
116:  * @var Controller
117:  */
118:     public $controller = null;
119: 
120: /**
121:  * Automatically mock controllers that aren't mocked
122:  *
123:  * @var boolean
124:  */
125:     public $autoMock = true;
126: 
127: /**
128:  * Use custom routes during tests
129:  *
130:  * @var boolean
131:  */
132:     public $loadRoutes = true;
133: 
134: /**
135:  * The resulting view vars of the last testAction call
136:  *
137:  * @var array
138:  */
139:     public $vars = null;
140: 
141: /**
142:  * The resulting rendered view of the last testAction call
143:  *
144:  * @var string
145:  */
146:     public $view = null;
147: 
148: /**
149:  * The resulting rendered layout+view of the last testAction call
150:  *
151:  * @var string
152:  */
153:     public $contents = null;
154: 
155: /**
156:  * The returned result of the dispatch (requestAction), if any
157:  *
158:  * @var string
159:  */
160:     public $result = null;
161: 
162: /**
163:  * The headers that would have been sent by the action
164:  *
165:  * @var string
166:  */
167:     public $headers = null;
168: 
169: /**
170:  * Flag for checking if the controller instance is dirty.
171:  * Once a test has been run on a controller it should be rebuilt
172:  * to clean up properties.
173:  *
174:  * @var boolean
175:  */
176:     protected $_dirtyController = false;
177: 
178: /**
179:  * Used to enable calling ControllerTestCase::testAction() without the testing
180:  * framework thinking that it's a test case
181:  *
182:  * @param string $name The name of the function
183:  * @param array $arguments Array of arguments
184:  * @return the return of _testAction
185:  * @throws BadMethodCallException when you call methods that don't exist.
186:  */
187:     public function __call($name, $arguments) {
188:         if ($name === 'testAction') {
189:             return call_user_func_array(array($this, '_testAction'), $arguments);
190:         }
191:         throw new BadMethodCallException("Method '{$name}' does not exist.");
192:     }
193: 
194: /**
195:  * Lets you do functional tests of a controller action.
196:  *
197:  * ### Options:
198:  *
199:  * - `data` Will be used as the request data. If the `method` is GET,
200:  *   data will be used a GET params. If the `method` is POST, it will be used
201:  *   as POST data. By setting `$options['data']` to a string, you can simulate XML or JSON
202:  *   payloads to your controllers allowing you to test REST webservices.
203:  * - `method` POST or GET. Defaults to POST.
204:  * - `return` Specify the return type you want. Choose from:
205:  *     - `vars` Get the set view variables.
206:  *     - `view` Get the rendered view, without a layout.
207:  *     - `contents` Get the rendered view including the layout.
208:  *     - `result` Get the return value of the controller action. Useful
209:  *       for testing requestAction methods.
210:  *
211:  * @param string $url The url to test
212:  * @param array $options See options
213:  * @return mixed
214:  */
215:     protected function _testAction($url = '', $options = array()) {
216:         $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
217: 
218:         $options = array_merge(array(
219:             'data' => array(),
220:             'method' => 'POST',
221:             'return' => 'result'
222:         ), $options);
223: 
224:         $restore = array('get' => $_GET, 'post' => $_POST);
225: 
226:         $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
227:         if (is_array($options['data'])) {
228:             if (strtoupper($options['method']) === 'GET') {
229:                 $_GET = $options['data'];
230:                 $_POST = array();
231:             } else {
232:                 $_POST = $options['data'];
233:                 $_GET = array();
234:             }
235:         }
236:         $request = $this->getMock('CakeRequest', array('_readInput'), array($url));
237: 
238:         if (is_string($options['data'])) {
239:             $request->expects($this->any())
240:                 ->method('_readInput')
241:                 ->will($this->returnValue($options['data']));
242:         }
243: 
244:         $Dispatch = new ControllerTestDispatcher();
245:         foreach (Router::$routes as $route) {
246:             if ($route instanceof RedirectRoute) {
247:                 $route->response = $this->getMock('CakeResponse', array('send'));
248:             }
249:         }
250:         $Dispatch->loadRoutes = $this->loadRoutes;
251:         $Dispatch->parseParams(new CakeEvent('ControllerTestCase', $Dispatch, array('request' => $request)));
252:         if (!isset($request->params['controller']) && Router::currentRoute()) {
253:             $this->headers = Router::currentRoute()->response->header();
254:             return;
255:         }
256:         if ($this->_dirtyController) {
257:             $this->controller = null;
258:         }
259: 
260:         $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
261:         if ($this->controller === null && $this->autoMock) {
262:             $this->generate($plugin . Inflector::camelize($request->params['controller']));
263:         }
264:         $params = array();
265:         if ($options['return'] === 'result') {
266:             $params['return'] = 1;
267:             $params['bare'] = 1;
268:             $params['requested'] = 1;
269:         }
270:         $Dispatch->testController = $this->controller;
271:         $Dispatch->response = $this->getMock('CakeResponse', array('send'));
272:         $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
273:         $this->controller = $Dispatch->testController;
274:         $this->vars = $this->controller->viewVars;
275:         $this->contents = $this->controller->response->body();
276:         if (isset($this->controller->View)) {
277:             $this->view = $this->controller->View->fetch('__view_no_layout__');
278:         }
279:         $this->_dirtyController = true;
280:         $this->headers = $Dispatch->response->header();
281: 
282:         $_GET = $restore['get'];
283:         $_POST = $restore['post'];
284: 
285:         return $this->{$options['return']};
286:     }
287: 
288: /**
289:  * Generates a mocked controller and mocks any classes passed to `$mocks`. By
290:  * default, `_stop()` is stubbed as is sending the response headers, so to not
291:  * interfere with testing.
292:  *
293:  * ### Mocks:
294:  *
295:  * - `methods` Methods to mock on the controller. `_stop()` is mocked by default
296:  * - `models` Models to mock. Models are added to the ClassRegistry so any
297:  *   time they are instantiated the mock will be created. Pass as key value pairs
298:  *   with the value being specific methods on the model to mock. If `true` or
299:  *   no value is passed, the entire model will be mocked.
300:  * - `components` Components to mock. Components are only mocked on this controller
301:  *   and not within each other (i.e., components on components)
302:  *
303:  * @param string $controller Controller name
304:  * @param array $mocks List of classes and methods to mock
305:  * @return Controller Mocked controller
306:  * @throws MissingControllerException When controllers could not be created.
307:  * @throws MissingComponentException When components could not be created.
308:  */
309:     public function generate($controller, $mocks = array()) {
310:         list($plugin, $controller) = pluginSplit($controller);
311:         if ($plugin) {
312:             App::uses($plugin . 'AppController', $plugin . '.Controller');
313:             $plugin .= '.';
314:         }
315:         App::uses($controller . 'Controller', $plugin . 'Controller');
316:         if (!class_exists($controller . 'Controller')) {
317:             throw new MissingControllerException(array(
318:                 'class' => $controller . 'Controller',
319:                 'plugin' => substr($plugin, 0, -1)
320:             ));
321:         }
322:         ClassRegistry::flush();
323: 
324:         $mocks = array_merge_recursive(array(
325:             'methods' => array('_stop'),
326:             'models' => array(),
327:             'components' => array()
328:         ), (array)$mocks);
329: 
330:         list($plugin, $name) = pluginSplit($controller);
331:         $controllerObj = $this->getMock($name . 'Controller', $mocks['methods'], array(), '', false);
332:         $controllerObj->name = $name;
333:         $request = $this->getMock('CakeRequest');
334:         $response = $this->getMock('CakeResponse', array('_sendHeader'));
335:         $controllerObj->__construct($request, $response);
336:         $controllerObj->Components->setController($controllerObj);
337: 
338:         $config = ClassRegistry::config('Model');
339:         foreach ($mocks['models'] as $model => $methods) {
340:             if (is_string($methods)) {
341:                 $model = $methods;
342:                 $methods = true;
343:             }
344:             if ($methods === true) {
345:                 $methods = array();
346:             }
347:             $this->getMockForModel($model, $methods, $config);
348:         }
349: 
350:         foreach ($mocks['components'] as $component => $methods) {
351:             if (is_string($methods)) {
352:                 $component = $methods;
353:                 $methods = true;
354:             }
355:             if ($methods === true) {
356:                 $methods = array();
357:             }
358:             list($plugin, $name) = pluginSplit($component, true);
359:             $componentClass = $name . 'Component';
360:             App::uses($componentClass, $plugin . 'Controller/Component');
361:             if (!class_exists($componentClass)) {
362:                 throw new MissingComponentException(array(
363:                     'class' => $componentClass
364:                 ));
365:             }
366:             $config = isset($controllerObj->components[$component]) ? $controllerObj->components[$component] : array();
367:             $componentObj = $this->getMock($componentClass, $methods, array($controllerObj->Components, $config));
368:             $controllerObj->Components->set($name, $componentObj);
369:             $controllerObj->Components->enable($name);
370:         }
371: 
372:         $controllerObj->constructClasses();
373:         $this->_dirtyController = false;
374: 
375:         $this->controller = $controllerObj;
376:         return $this->controller;
377:     }
378: 
379: }
380: 
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs