【问题标题】:Why isAuthorized() is never called when running Controller tests?为什么在运行控制器测试时从不调用 isAuthorized()?
【发布时间】:2012-05-21 15:47:38
【问题描述】:

我正在尝试在我的一个控制器中测试授权,以确保只有特定类型的用户才能访问某些操作。但是在运行测试时从不调用 AppController 上的 isAuthorized() 方法。该方法如下所示:

public function isAuthorized($user = null){
    if(!isset($this->request->params['admin'])){
        return true;
    }

    return in_array($user['role'], array('admin', 'root'));
}

我的测试功能:

public function testArticlesIndex() {
    $this->generate('Articles', array(
        'components' => array('Auth')
    ));

    $this->testAction('/admin/articles', array('return' => 'view'));
    $this->assertEmpty($this->view);
}

我尝试了很多模拟 AuthComponent 而不是模拟它的东西。我无法重现这种情况,这需要 isAuthorized(),在这种情况下,具有 admin 或 root 以外角色的用户尝试访问 admin 上的操作并失败。

【问题讨论】:

  • 那你如何模拟当前会话用户呢?我认为最干净的方法是直接使用模拟参数/模拟请求测试 isAuthorized。

标签: cakephp testing authentication controller phpunit


【解决方案1】:

当您在未定义要模拟的方法的情况下模拟 Auth 组件时,默认情况下,所有方法都会被模拟。解决方案是模拟您希望模拟的特定 AuthComponent 方法:

 $this->generate('Articles', array(
   'components' => array(
     'Auth' => array(
       'redirect' // only mocks AuthComponent::redirect()
     )
   )
 ));

从书中:

您可以选择不向其传递方法来存根整个类, 如上例中的 Session。

见:http://book.cakephp.org/2.0/en/development/testing.html#using-mocks-with-testaction

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多