在CakePHP 2测试用例中处理安全组件 [英] Dealing with Security component in a CakePHP 2 test case

查看:67
本文介绍了在CakePHP 2测试用例中处理安全组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试CakePHP操作,该操作处理使用Security组件保护的注册表单.我已经在UsersController中配置了组件,如下所示:

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'));

但是测试坚持使用POST请求的Security验证.我正在使用CakePHP 2.0.3和PHPUnit 3.6.3.

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

顺便说一句,我不是直接使用UsersController,而是CakePHP为我烘焙的TestUsersController类(我认为是对generate方法的替代).

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?

推荐答案

解决方案是模拟Users控制器和User模型并期望Security::_validatePost()方法:

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));

这篇关于在CakePHP 2测试用例中处理安全组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆