I was trying to learn how to use unit testing in CakePhp, I'm trying to write a controller test. I read about testAction() and debug() function, but It doesn't work for me, I mean, the test method passes, but the debug() returns null (because testAction does)
This is my code:
<?php
App::uses('Controller', 'Controller');
App::uses('View', 'View');
App::uses('PostsController', 'Controller');
class PostsControllerTest extends ControllerTestCase {
public function setUp() {
parent::setUp();
$Controller = new Controller();
$View = new View($Controller);
$this->Posts = new PostsController($View);
}
public function testIndex() {
$result = $this->testAction('Posts/Index');
debug($result);
}
}
Posts/index controller returns a list of all posts stored in the DB.
I'm assuming you're using CakePHP 2.
$this->testAction()
can return a few different results, depending on the options you give it.
For example, if you set the return
option to vars
, the testAction()
method will return an array of the vars that have been set in the tested action:
public function testIndex() {
$result = $this->testAction('/posts/index', array('return' => 'vars'));
debug($result);
}
In this example, the debug data should be an array of the vars that you set in the /posts/index
action.
The CakePHP documentation describes the possible results that you can have returned here: http://book.cakephp.org/2.0/en/development/testing.html#choosing-the-return-type
Note that the default option, result
, gives you the value that your controller action returns. For most controller actions this will be null
, so the fact that you're getting null
in your example is to be expected.
mtnorthrop's answer did work for me, but only once I also dealt with my site's authorization as well. If your site uses authorization, then testAction('/action', array('return' => 'contents') will return null. I've seen a few solutions for this:
One is to follow the solution given here: CakePHP Unit Test Not Returning Content or View where you check in AppController::beforeFilter() whether you are in debug mode, and if so, always authenticate the user:
// For Mock Objects and Debug >= 2 allow all (this is for PHPUnit Tests)
if(preg_match('/Mock_/',get_class($this)) && Configure::read('debug') >= 2){
$this->Auth->allow();
}
Another is to follow the suggestions given in this discussion: https://groups.google.com/forum/#!topic/cake-php/eWCO2bf5t98 and to mock the Auth object using the ControllerTestCase's generate function:
class MyControllerTest extends ControllerTestCase {
public function setUp() {
parent::setUp();
$this->controller = $this->generate('My',
array('components' => array(
'Auth' => array('isAuthorized')
))
);
$this->controller->Auth->expects($this->any())
->method('isAuthorized')
->will($this->returnValue(true));
}
}
Note (I'm using CakePhp 2.3.8)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With