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.1 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.1
      • 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
    • Network
      • Email
      • Http
    • Routing
      • 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:  * PHP 5
  6:  *
  7:  * CakePHP(tm) Tests <http://book.cakephp.org/2.0/en/development/testing.html>
  8:  * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9:  *
 10:  * Licensed under The MIT License
 11:  * Redistributions of files must retain the above copyright notice
 12:  *
 13:  * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 14:  * @link          http://book.cakephp.org/2.0/en/development/testing.html CakePHP(tm) Tests
 15:  * @package       Cake.TestSuite
 16:  * @since         CakePHP(tm) v 2.0
 17:  * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 18:  */
 19: 
 20: App::uses('Dispatcher', 'Routing');
 21: App::uses('CakeTestCase', 'TestSuite');
 22: App::uses('Router', 'Routing');
 23: App::uses('CakeRequest', 'Network');
 24: App::uses('CakeResponse', 'Network');
 25: App::uses('Helper', 'View');
 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->attached() 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:  */
 98:     public function afterRender($viewFile) {
 99:         $this->_View->assign('__view_no_layout__', $this->_View->fetch('content'));
100:         $this->_View->Helpers->unload('InterceptContent');
101:     }
102: 
103: }
104: 
105: /**
106:  * ControllerTestCase class
107:  *
108:  * @package       Cake.TestSuite
109:  */
110: abstract class ControllerTestCase extends CakeTestCase {
111: 
112: /**
113:  * The controller to test in testAction
114:  *
115:  * @var Controller
116:  */
117:     public $controller = null;
118: 
119: /**
120:  * Automatically mock controllers that aren't mocked
121:  *
122:  * @var boolean
123:  */
124:     public $autoMock = true;
125: 
126: /**
127:  * Use custom routes during tests
128:  *
129:  * @var boolean
130:  */
131:     public $loadRoutes = true;
132: 
133: /**
134:  * The resulting view vars of the last testAction call
135:  *
136:  * @var array
137:  */
138:     public $vars = null;
139: 
140: /**
141:  * The resulting rendered view of the last testAction call
142:  *
143:  * @var string
144:  */
145:     public $view = null;
146: 
147: /**
148:  * The resulting rendered layout+view of the last testAction call
149:  *
150:  * @var string
151:  */
152:     public $contents = null;
153: 
154: /**
155:  * The returned result of the dispatch (requestAction), if any
156:  *
157:  * @var string
158:  */
159:     public $result = null;
160: 
161: /**
162:  * The headers that would have been sent by the action
163:  *
164:  * @var string
165:  */
166:     public $headers = null;
167: 
168: /**
169:  * Flag for checking if the controller instance is dirty.
170:  * Once a test has been run on a controller it should be rebuilt
171:  * to clean up properties.
172:  *
173:  * @var boolean
174:  */
175:     private $__dirtyController = false;
176: 
177: /**
178:  * Used to enable calling ControllerTestCase::testAction() without the testing
179:  * framework thinking that it's a test case
180:  *
181:  * @param string $name The name of the function
182:  * @param array $arguments Array of arguments
183:  * @return Function
184:  */
185:     public function __call($name, $arguments) {
186:         if ($name == 'testAction') {
187:             return call_user_func_array(array($this, '_testAction'), $arguments);
188:         }
189:     }
190: 
191: /**
192:  * Lets you do functional tests of a controller action.
193:  *
194:  * ### Options:
195:  *
196:  * - `data` Will be used as the request data.  If the `method` is GET,
197:  *   data will be used a GET params.  If the `method` is POST, it will be used
198:  *   as POST data. By setting `$options['data']` to a string, you can simulate XML or JSON
199:  *   payloads to your controllers allowing you to test REST webservices.
200:  * - `method` POST or GET. Defaults to POST.
201:  * - `return` Specify the return type you want.  Choose from:
202:  *     - `vars` Get the set view variables.
203:  *     - `view` Get the rendered view, without a layout.
204:  *     - `contents` Get the rendered view including the layout.
205:  *     - `result` Get the return value of the controller action.  Useful
206:  *       for testing requestAction methods.
207:  *
208:  * @param string $url The url to test
209:  * @param array $options See options
210:  */
211:     protected function _testAction($url = '', $options = array()) {
212:         $this->vars = $this->result = $this->view = $this->contents = $this->headers = null;
213: 
214:         $options = array_merge(array(
215:             'data' => array(),
216:             'method' => 'POST',
217:             'return' => 'result'
218:         ), $options);
219: 
220:         $restore = array('get' => $_GET, 'post' => $_POST);
221: 
222:         $_SERVER['REQUEST_METHOD'] = strtoupper($options['method']);
223:         if (is_array($options['data'])) {
224:             if (strtoupper($options['method']) == 'GET') {
225:                 $_GET = $options['data'];
226:                 $_POST = array();
227:             } else {
228:                 $_POST = $options['data'];
229:                 $_GET = array();
230:             }
231:         }
232:         $request = $this->getMock('CakeRequest', array('_readInput'), array($url));
233: 
234:         if (is_string($options['data'])) {
235:             $request->expects($this->any())
236:                 ->method('_readInput')
237:                 ->will($this->returnValue($options['data']));
238:         }
239: 
240:         $Dispatch = new ControllerTestDispatcher();
241:         foreach (Router::$routes as $route) {
242:             if ($route instanceof RedirectRoute) {
243:                 $route->response = $this->getMock('CakeResponse', array('send'));
244:             }
245:         }
246:         $Dispatch->loadRoutes = $this->loadRoutes;
247:         $request = $Dispatch->parseParams($request);
248:         if (!isset($request->params['controller'])) {
249:             $this->headers = Router::currentRoute()->response->header();
250:             return;
251:         }
252:         if ($this->__dirtyController) {
253:             $this->controller = null;
254:         }
255: 
256:         $plugin = empty($request->params['plugin']) ? '' : Inflector::camelize($request->params['plugin']) . '.';
257:         if ($this->controller === null && $this->autoMock) {
258:             $this->generate($plugin . Inflector::camelize($request->params['controller']));
259:         }
260:         $params = array();
261:         if ($options['return'] == 'result') {
262:             $params['return'] = 1;
263:             $params['bare'] = 1;
264:             $params['requested'] = 1;
265:         }
266:         $Dispatch->testController = $this->controller;
267:         $Dispatch->response = $this->getMock('CakeResponse', array('send'));
268:         $this->result = $Dispatch->dispatch($request, $Dispatch->response, $params);
269:         $this->controller = $Dispatch->testController;
270:         $this->vars = $this->controller->viewVars;
271:         $this->contents = $this->controller->response->body();
272:         if (isset($this->controller->View)) {
273:             $this->view = $this->controller->View->fetch('__view_no_layout__');
274:         }
275:         $this->__dirtyController = true;
276:         $this->headers = $Dispatch->response->header();
277: 
278:         $_GET = $restore['get'];
279:         $_POST = $restore['post'];
280: 
281:         return $this->{$options['return']};
282:     }
283: 
284: /**
285:  * Generates a mocked controller and mocks any classes passed to `$mocks`. By
286:  * default, `_stop()` is stubbed as is sending the response headers, so to not
287:  * interfere with testing.
288:  *
289:  * ### Mocks:
290:  *
291:  * - `methods` Methods to mock on the controller. `_stop()` is mocked by default
292:  * - `models` Models to mock. Models are added to the ClassRegistry so they any
293:  *   time they are instantiated the mock will be created. Pass as key value pairs
294:  *   with the value being specific methods on the model to mock. If `true` or
295:  *   no value is passed, the entire model will be mocked.
296:  * - `components` Components to mock. Components are only mocked on this controller
297:  *   and not within each other (i.e., components on components)
298:  *
299:  * @param string $controller Controller name
300:  * @param array $mocks List of classes and methods to mock
301:  * @return Controller Mocked controller
302:  * @throws MissingControllerException When controllers could not be created.
303:  * @throws MissingComponentException When components could not be created.
304:  */
305:     public function generate($controller, $mocks = array()) {
306:         list($plugin, $controller) = pluginSplit($controller);
307:         if ($plugin) {
308:             App::uses($plugin . 'AppController', $plugin . '.Controller');
309:             $plugin .= '.';
310:         }
311:         App::uses($controller . 'Controller', $plugin . 'Controller');
312:         if (!class_exists($controller . 'Controller')) {
313:             throw new MissingControllerException(array(
314:                 'class' => $controller . 'Controller',
315:                 'plugin' => substr($plugin, 0, -1)
316:             ));
317:         }
318:         ClassRegistry::flush();
319: 
320:         $mocks = array_merge_recursive(array(
321:             'methods' => array('_stop'),
322:             'models' => array(),
323:             'components' => array()
324:         ), (array)$mocks);
325: 
326:         list($plugin, $name) = pluginSplit($controller);
327:         $_controller = $this->getMock($name . 'Controller', $mocks['methods'], array(), '', false);
328:         $_controller->name = $name;
329:         $request = $this->getMock('CakeRequest');
330:         $response = $this->getMock('CakeResponse', array('_sendHeader'));
331:         $_controller->__construct($request, $response);
332: 
333:         $config = ClassRegistry::config('Model');
334:         foreach ($mocks['models'] as $model => $methods) {
335:             if (is_string($methods)) {
336:                 $model = $methods;
337:                 $methods = true;
338:             }
339:             if ($methods === true) {
340:                 $methods = array();
341:             }
342:             ClassRegistry::init($model);
343:             list($plugin, $name) = pluginSplit($model);
344:             $config = array_merge((array)$config, array('name' => $model));
345:             $_model = $this->getMock($name, $methods, array($config));
346:             ClassRegistry::removeObject($name);
347:             ClassRegistry::addObject($name, $_model);
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:             $_component = $this->getMock($componentClass, $methods, array(), '', false);
367:             $_controller->Components->set($name, $_component);
368:         }
369: 
370:         $_controller->constructClasses();
371:         $this->__dirtyController = false;
372: 
373:         $this->controller = $_controller;
374:         return $this->controller;
375:     }
376: 
377: }
378: 
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