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

时间:2015-05-18 17:28:55

标签: php unit-testing cakephp cakephp-3.0

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

我尝试使用$this->session()中的$this->assertResponseOk()设置会话数据,但是当我使用<?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(); } } 测试响应代码时,phpunit始终会返回错误:

  

状态代码不在200到204之间

     

断言302等于204或小于204。

这是我的简单测试:

beforeFilter()

我的AppController加载AuthComponent并使用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); } 配置autorize方法:

$answer = json_encode(array('players', 'scores'));
$answer->players = $arrayPlayers;
$answer->scores= $arrayScores;

有什么问题?

1 个答案:

答案 0 :(得分:1)

用户会话数据运行良好。

问题出在我的Mongoose: logs.ensureIndex({ name: 1 }) { background: true, safe: undefined } 方法中,它始终返回isAuthorized()并强制重定向。

相关问题