我正在为我的 UsersController 编写单元测试,以便用户只能编辑他们自己的个人资料。我正在使用 CakePHP 2.4.2 和带有控制器授权的 AuthComponent 来执行此操作。
授权配置:
public $components = array(
'Auth' => array(
'loginRedirect' => '/',
'logoutRedirect' => '/',
'authenticate' => array('Ldap'),
'authError' => 'You are not allowed to access this page',
'authorize' => 'Controller'));
用户控制器中的 isAuthorized():
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);
}
Expectation failed for method name is equal to <string:loggedIn> when invoked 1 time(s). Method was expected to be called 1 times, actually called 0 times.
当我运行测试时,我得到了。此外,当我将 this->once() 更改为 $this->any() 并将 $test 数组中的 id 更改为 2 时,这种情况应该会失败并从浏览器执行,但它成功通过了测试。
结合这些,似乎 isAuthorized() 在单元测试期间没有被调用。我很茫然。感谢您提供的任何帮助。