Dealing with Security component in a CakePHP 2 tes

2020-05-09 11:58发布

问题:

I am trying to test a CakePHP action that deals with a signup form secured with the Security component. I have configured the component in a UsersController like this:

public $components = array(
  'Security' => array('unlockedFields' => array('password_again')),
);

I can execute the action in a browser, but whenever I run the test case it fails with the following message:

"The request has been black-holed"

I have tried to disable the validation inside the test case in several ways:

$this->Users->Security->enable = false;
$this->Users->Security->validatePost = false;
$this->Users->Components->disable('Security');
$this->Users->Security = null; // desperate measure :)

// still fails
$this->testAction('/signup', array('data' => array(...), 'return' => 'contents'));

But the test insists in using the Security validation of POST request. I am using CakePHP 2.0.3 and PHPUnit 3.6.3.

By the way, I am not using the UsersController directly, but a TestUsersController class that CakePHP baked for me (as a replacement for generate method, I think).

What's the right way of dealing with Security component in a test case?

回答1:

The solution is to mock the Users controller and the User model and make expectations for the Security::_validatePost() method:

$this->Users = $this->generate(
  'Users',
  array(
    'components' => array(
      'Security' => array('_validatePost'),
    ),
    'models' => array('User' => true),
  )
);
$this->Users->Security->expects($this->any())
  ->method('_validatePost')
  ->will($this->returnValue(true));