【发布时间】:2020-07-08 10:40:31
【问题描述】:
我有一个尝试登录并获取详细信息的测试。我需要在此操作的请求标头中传递一个不记名令牌。请看下面的代码。我可以看到标题很少有我设置的标题。谁能给我指点来解决这个问题?
我正在使用 Laravel 7.2.2、PHP 7.4,
我正在运行 php artisan 测试
代码:
public function a_user_can_get_details()
{
$this->create_user();
$response = $this->json('POST',
'/api/login',
[
"email" => "john.doe@example.com",
"password" => "john123"
]);
$response->assertSuccessful();
$token = Str::replaceLast('"', '', Str::replaceFirst('"', '', $response->getContent()));
$headers = [
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $token
];
$response = $this->withHeaders($headers)
->get('api/user');
$response->assertSuccessful();
$this->assertCount(1, User::all());
}
这是我得到的错误。实际上,测试必须通过。那就是正确的用户名和密码:
Response status code [403] is not a successful status code. Failed asserting that false is true.
at tests/Feature/UserTest.php:141
137|
138| $response = $this->withHeaders($headers)
139| ->get('api/user');
140|
> 141| $response->assertSuccessful();
142| $this->assertCount(1, User::all());
143|
144| }
145|
【问题讨论】:
-
您是否可以在
create_user函数上登录用户? -
我没有在 create_user 中登录。
private function create_user(){ return $this->post('/api/user', [ "name" => "John Doe", "email" => "john.doe@example.com", "password" => "john123", "password_confirmation" => "john123" ]); } -
你们有中间件吗?由于您收到 403,我认为这是由中间件提供的权限错误。
-
我正在使用 sanctum 进行身份验证。除了默认的中间件 + sanctum + spatie 权限外,没有其他中间件在起作用。此外,我发现字符串操作存在问题。我改变了那个。现在我得到 401。下面是具有标题的 dd 摘录:` #headers: array:3 [ "cache-control" => array:1 [ 0 => "no-cache, private" ] "date" = > 数组:1 [ 0 => “星期六,2020 年 3 月 28 日 03:05:31 GMT”] “内容类型” => 数组:1 [ 0 => “应用程序/json”] `
标签: php laravel unit-testing