【发布时间】:2015-07-30 07:50:28
【问题描述】:
我正在尝试在 CakePHP 3.0 中运行单元测试,但所有操作都需要身份验证。
我尝试使用$this->session() 设置会话数据,就像在official documentation here 中一样,但是当我使用$this->assertResponseOk() 测试响应代码时,phpunit 总是返回错误:
状态码不在 200 和 204 之间
断言 302 等于 204 或小于 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);
}
怎么了?
【问题讨论】:
-
找出它重定向的原因。但是会话本身应该能够“让它认为”这个用户已经登录。我也会对 URL 使用数组语法,这样你就可以确定路由是你所期望的。可以在单独的测试用例中测试作为字符串的 URL。
-
谢谢@mark,你是对的。问题不是来自“假”会话数据。
isAuthorized()方法,总是返回false,强制重定向。
标签: php unit-testing cakephp cakephp-3.0