我试图学习如何在CakePhp中使用单元测试,我正在尝试编写一个控制器测试。我读过testAction()和debug()函数,但它对我不起作用,我的意思是,测试方法通过了,但debug(
这是我的代码:
<?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);
}
}
帖子/索引控制器返回存储在数据库中的所有帖子的列表。
我假设您使用的是CakePHP 2。
$this->testAction()
可以返回一些不同的结果,这取决于您给它的选项
例如,如果将return
选项设置为vars
,则testAction()
方法将返回在测试操作中设置的变量数组:
public function testIndex() {
$result = $this->testAction('/posts/index', array('return' => 'vars'));
debug($result);
}
在本例中,调试数据应该是您在/posts/index
操作中设置的变量的数组。
CakePHP文档描述了您可以在此处返回的可能结果:http://book.cakephp.org/2.0/en/development/testing.html#choosing-返回型
请注意,默认选项result
为您提供控制器操作返回的值。对于大多数控制器操作,这将是null
,因此在您的示例中得到null
是意料之中的事。
mtnorthrop的回答确实对我有效,但只有一次我还处理了我的网站授权。如果您的网站使用授权,那么testAction("/action",array("return"=>"contents")将返回null。我看到了一些解决方案:
一种是遵循此处给出的解决方案:CakePHP单元测试不返回内容或视图在AppController::beforeFilter()中检查是否处于调试模式,如果是,则始终验证用户:
// 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();
}
另一个是遵循本次讨论中给出的建议:https://groups.google.com/forum/#!主题/蛋糕php/eWCO2bf5t98并使用ControllerTestCase的生成函数模拟Auth对象:
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));
}
}
注意(我使用CakePhp 2.3.8)