cakephp控制器测试 - 如何测试需要授权的操作?

时间:2011-02-22 16:14:30

标签: php unit-testing authorization cakephp-1.3 simpletest

标题几乎说明了一切。我想试试,例如UsersController::admin_index()操作,但需要授权用户访问此位置,因此当我运行测试时,它会将我发送到登录页面,即使我手动登录,也不会进行任何测试。

那么如何在不编辑实际授权码的情况下强制蛋糕跳过授权?

顺便说一句,如果它有帮助,我的testAdminIndex()代码如下所示:

function testAdminIndex() {     
    $result = $this->testAction('/admin/users/index');      
    debug($result); 
}

2 个答案:

答案 0 :(得分:5)

这里有一篇文章涵盖了这个主题......

http://mark-story.com/posts/view/testing-cakephp-controllers-the-hard-way

建议在为经过身份验证的用户添加会话值后,完全绕过“testAction”并手动执行请求。示例如下......

function testAdminEdit() {
    $this->Posts->Session->write('Auth.User', array(
        'id' => 1,
        'username' => 'markstory',
    ));
    $this->Posts->data = array(
        'Post' => array(
            'id' => 2,
            'title' => 'Best article Evar!',
            'body' => 'some text',
        ),
        'Tag' => array(
            'Tag' => array(1,2,3),
        )
    );
    $this->Posts->params = Router::parse('/admin/posts/edit/2');
    $this->Posts->beforeFilter();
    $this->Posts->Component->startup($this->Posts);
    $this->Posts->admin_edit();
}

答案 1 :(得分:1)

这是关于cakephp测试文档的。

http://book.cakephp.org/3.0/en/development/testing.html#testing-actions-that-require-authentication

测试需要身份验证的操作 如果您使用的是AuthComponent,则需要存根AuthComponent用于验证用户身份的会话数据。您可以在IntegrationTestCase中使用帮助器方法来执行此操作。假设您有一个包含add方法的ArticlesController,并且该方法需要进行身份验证,那么您可以编写以下测试:

public function testAddUnauthenticatedFails()
{
    // No session data set.
    $this->get('/articles/add');

    $this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
}

public function testAddAuthenticated()
{
    // Set session data
    $this->session([
        'Auth' => [
            'User' => [
                'id' => 1,
                'username' => 'testing',
                // other keys.
            ]
        ]
    ]);
    $this->get('/articles/add');

    $this->assertResponseOk();
    // Other assertions.
}

我用过这个

// Set session data
$this->session(['Auth.User.id' => 1]);

我实际上有角色所以我的解决方案看起来像这样:

public function testDisplay()
{
 $this->session(['Auth.User.id' => 1, 'Auth.User.role' => 'admin']);

    $this->get('/pages/home');
    $this->assertResponseOk();
    $this->assertResponseContains('CakePHP');
    $this->assertResponseContains('<html>');
}