4

标题基本概括了所有内容。我想测试例如UsersController::admin_index()操作,但是用户需要被授权访问该位置,因此当我运行测试时,它会将我发送到登录页面,即使我手动登录,也没有完成任何测试。

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

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

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

2 回答 2

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();
}
于 2011-02-25T13:00:44.807 回答
2

这是 cakephp 测试文档。

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

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

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>');
}
于 2016-03-03T11:01:31.510 回答