[英]CakePHP 3.x - Testing actions that require Authentication
我正在嘗試在CakePHP 3.0中運行單元測試,但是所有操作都需要身份驗證。
我試圖像這里的官方文檔一樣使用$this->session()
設置會話數據,但是當我使用$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);
}
怎么了 ?
用戶會話數據運行良好。
問題出在我的isAuthorized()
方法內部,該方法始終返回false
和強制重定向。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.