这是 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>');
}