Unit testing CakePHP&AuthComponent单元测试似乎没有调用isAuthorized()
我正在为我的UsersController编写单元测试,以便用户只能编辑自己的配置文件。我正在使用CakePHP2.4.2和AuthComponent与Controller authorize来完成这项工作 身份验证配置:Unit testing CakePHP&AuthComponent单元测试似乎没有调用isAuthorized(),unit-testing,cakephp,authentication,authorization,Unit Testing,Cakephp,Authentication,Authorization,我正在为我的UsersController编写单元测试,以便用户只能编辑自己的配置文件。我正在使用CakePHP2.4.2和AuthComponent与Controller authorize来完成这项工作 身份验证配置: public $components = array( 'Auth' => array( 'loginRedirect' => '/',
public $components = array(
'Auth' => array(
'loginRedirect' => '/',
'logoutRedirect' => '/',
'authenticate' => array('Ldap'),
'authError' => 'You are not allowed to access this page',
'authorize' => 'Controller'));
已在UsersController中授权:
public function isAuthorized($user = null) {
if($this->Auth->loggedIn()) {
return $this->request->params['pass'][0] == $user['id'];
}
return false;
}
编辑的单元测试:
public function testEdit() {
$result = $this->testAction('/users/view/1', array('return' => 'view'));
$this->assertRegExp('/Adam C Hobaugh/', $result);
$user = $this->generate('Users', array(
'components' => array(
'Session',
'Auth' => array('user'))));
$test = array('id' => 1);
$user->Auth->expects($this->once())->method('loggedIn')
->with($this->returnValue(true));
$user->Auth->expects($this->any())->method('user')
->with($this->returnValue($test));
$user->Session->expects($this->any())->method('setFlash');
$result = $this->testAction('/users/edit/1', array(
'return' => 'headers',
'data' => array('User' => array( {user array} ))));
debug($result);
$this->assertContains('/users', @$result['Location']);
$result = $this->testAction('/users/view/1', array('return' => 'view'));
$this->assertRegExp('/John Jacob Doe/', $result);
}
当调用1次时,我发现方法名等于的期望值失败。方法应被调用1次,实际调用0次。当我运行测试时。另外,当我将this->once更改为$this->any,并将$test数组中的id更改为2时(这种情况应该会失败,并且会从浏览器中执行),它成功地通过了测试
如果将这些组合在一起,则在单元测试期间似乎没有调用isAuthorized。我不知所措。感谢您提供的帮助。首先:在测试代码中,您调用的是view方法,而不是edit方法 第二:我授权不是为了这个。使用这种方法,您应该只定义谁可以访问什么功能,不应该有任何应用程序业务逻辑 第三:如果你想限制普通用户只编辑他们自己的个人资料,你应该把dit方法改成这样
public function edit() {
$this->request->data['User']['id'] = $this->Auth->User('id');
if ($this->request->is('post') || $this->request->is('put')) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash(__('The user has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
}
} else {
$this->request->data = array('User' => $this->Auth->User());
}
}
并删除echo$this->Form->input'id';从编辑视图
我正在写一本关于这个话题的书。它将很快在这里提供: