CakePHP 3.x - 测试需要身份验证的操作

CakePHP 3.x - Testing actions that require Authentication

我正在尝试 运行 在 CakePHP 3.0 中进行单元测试,但所有操作都需要身份验证。

我尝试使用 $this->session() 设置会话数据,就像在 official documentation here 中一样,但是当我使用 $this->assertResponseOk() 测试响应代码时,phpunit 总是 returns 错误:

Status code is not between 200 and 204

Failed asserting that 302 is equal to 204 or is less than 204.

这是我的简单测试:

<?php
namespace ContactManager\Test\TestCase\Controller;
use Cake\TestSuite\IntegrationTestCase;
use ContactManager\Controller\ContactsController;

/**
 * ContactManager\Controller\ContactsController Test Case
 */
class ContactsControllerTest extends IntegrationTestCase {

    public function setUserSession() {
        $auth = [
            'Auth' => [
                'User' => [
                    'id' => 2,
                    'email' => 'john.doe@crm.com',
                    'firstname' => 'John',
                    'lastname' => 'Doe',
                    'gender' => 'm',
                    'birthday' => '1975-08-01',
                    'state' => 1,
                    'created' => '2015-04-01 22:26:51',
                    'modified' => '2015-04-01 22:26:51'
                ]
            ]
        ];
        return $auth;
    }

    /**
     * Test index action
     *
     * @return void
     */
    public function testIndex() {
        $this->session($this->setUserSession());
        $this->get('/contacts/index');
        $this->assertResponseOk(); 
    }

}

我的 AppController 加载 AuthComponent 并使用 beforeFilter() 配置 autorize 方法:

public function initialize() {
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', ['authorize' => 'Controller',
        'loginAction' => [
            'prefix' => false,
            'controller' => 'Users',
            'action' => 'login'
        ],
        'loginRedirect' => [
            'prefix' => 'admin',
            'controller' => 'Pages',
            'action' => 'display',
            'dashboard'
        ],
        'logoutRedirect' => [
            'prefix' => false,
            'controller' => 'Users',
            'action' => 'login'
        ],
        'authenticate' => [
            'Form' => [
                'fields' => [
                    'username' => 'email',
                    'password' => 'password'
                ],
                'scope' => [
                    'Users.state' => 1
                ]
            ]
    ]]);
}

public function beforeFilter(\Cake\Event\Event $event) {
    $this->Auth->authorize = 'Controller';
    parent::beforeFilter($event);
}

怎么了?

用户会话数据运行良好。

问题出在我的 isAuthorized() 方法中,它总是返回 false 并强制重定向。