6

这是我的UsersController测试用例:

<?php
App::uses('UsersController', 'Controller');

class TestUsersController extends UsersController {

    public $autoRender = false;

    public function redirect($url, $status = null, $exit = true) {
        $this->redirectUrl = $url;
    }

    public function render($action = null, $layout = null, $file = null) {
        $this->renderedAction = $action;
    }

    public function _stop($status = 0) {
        $this->stopped = $status;
    }
}

class UsersControllerTestCase extends ControllerTestCase {

    public $fixtures = array('app.user');

    public function setUp() {
        parent::setUp();
        $this->Users = new TestUsersController();
        $this->Users->constructClasses();
    }

    public function tearDown() {
        unset($this->Users);

        parent::tearDown();
    }

    public function testAdminSearchStudents() {
        $data = array('User' => array('search' => 'Ipsum'));
        $result = $this->testAction('/admin', array('return' => 'vars', 'method' => 'post', 'data' => $data));
        $this->assertCount(1, $result['users']);
    }

}

我的 UsersController 没有什么特别之处,但它使用了 SecurityComponent(继承自 AppController)。

当我运行测试时,我得到了臭名昭著的:

请求已被黑洞测试用例:UsersControllerTestCase(testAdminSearchStudents)

我认为这是因为我正在伪造一个没有 CSRF 令牌和引用的 POST 请求?

我应该怎么做才能在不从控制器中删除安全组件的情况下完成这项工作?

我不确定这是否会有所帮助,但这是堆栈跟踪的重要部分:

/var/www/source/cakephp/lib/Cake/Controller/Component/SecurityComponent.php : 230
SecurityComponent::startup
/var/www/source/cakephp/lib/Cake/Utility/ObjectCollection.php : 130
ObjectCollection::trigger
/var/www/source/cakephp/lib/Cake/Event/CakeEventManager.php : 246
/var/www/source/cakephp/lib/Cake/Controller/Controller.php : 671
/var/www/source/cakephp/lib/Cake/Routing/Dispatcher.php : 183
/var/www/source/cakephp/lib/Cake/Routing/Dispatcher.php : 161
/var/www/source/cakephp/lib/Cake/TestSuite/ControllerTestCase.php : 271
ControllerTestCase::_testAction
/var/www/source/cakephp/lib/Cake/TestSuite/ControllerTestCase.php : 189

问候

4

1 回答 1

2

我解决了模拟SecurityComponent::_validatePost方法的问题:

$this->Users = $this->generate('Users', array(
    'components' => array(
        'Security' => array('_validatePost'),
    )
));

灵感来自在 CakePHP 2 测试用例中处理安全组件

于 2012-08-27T15:30:28.873 回答