在应用程序中启用了 authentication
中间件后,您需要在集成测试中模拟身份验证凭据。首先,确保您的控制器或中间件测试使用 IntegrationTestTrait
// In a controller test.
use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
class ArticlesControllerTest extends TestCase
{
use IntegrationTestTrait;
// Test methods and helpers to follow.
}
根据您使用的身份验证类型,您需要以不同的方式模拟凭据。让我们回顾一下几种常见的身份验证类型。
基于会话的身份验证需要模拟通常在会话中找到的用户数据。在您的测试用例中,您可以定义一个辅助方法来让您“登录”。
protected function login($userId = 1)
{
$users = TableRegistry::getTableLocator()->get('Users');
$user = $users->get($userId);
$this->session(['Auth' => $user]);
}
在您的集成测试中,您可以使用 login()
来模拟用户登录。
public function testGet()
{
$this->login();
$this->get('/bookmarks/1');
$this->assertResponseOk();
}
使用基于令牌的身份验证,您需要模拟 Authorization
标头。在获取有效令牌后,设置请求。
public function testGet()
{
$token = $this->getToken();
$this->configRequest([
'headers' => ['Authorization' => 'Bearer ' . $token]
]);
$this->get('/api/bookmarks');
$this->assertResponseOk();
}
在测试基本或摘要身份验证时,您可以添加 PHP 自动创建 的环境变量。
public function testGet()
{
$this->configRequest([
'environment' => [
'PHP_AUTH_USER' => 'username',
'PHP_AUTH_PW' => 'password',
]
]);
$this->get('/api/bookmarks');
$this->assertResponseOk();
}