我在测试Laravel 5.5时遇到了问题。我需要在TEST HEADER中发送一个Bearer Token,但是没有工作
public function testAuthCheckinvalidToken()
{
$response = $this->withHeaders([
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . $this->token,
])->json('GET', 'auth/check');
...
}
当我dd($ response)时,只设置了默认的HEADERS:
#headers: array:5 [
"cache-control" => array:1 [
0 => "no-cache, private"
]
"date" => array:1 [
0 => "Tue, 21 Nov 2017 18:48:27 GMT"
]
"content-type" => array:1 [
0 => "application/json"
]
"x-ratelimit-limit" => array:1 [
0 => 60
]
"x-ratelimit-remaining" => array:1 [
0 => 59
]
]
我的标题并没有出现。 我认为我是对的
答案 0 :(得分:4)
您在此处设置的标题显然是为了请求,对于响应,您从Laravel应用程序中获取标题,因此很明显您无法看到为请求设置的标题。
如果您想要查看此处设置的标题,则应在应用中运行dd($request);
,而不是在测试中运行。
修改强>
确认标题是否传递给应用程序整个测试代码:
<强>测试/ Feafure / ExampleTest.php 强>
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function testBasicTest()
{
$response = $this->withHeaders([
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'Authorization' => 'Bearer ' . 'abc',
])->json('GET', 'auth/check');
}
}
<强>路由/ web.php 强>
Route::get('auth/check', function() {
dd(request()->headers);
});
所以当我现在运行测试时:
./vendor/bin/phpunit
结果是:
Symfony\Component\HttpFoundation\HeaderBag {#49 #headers: array:8 [
"host" => array:1 [
0 => "localhost"
]
"user-agent" => array:1 [
0 => "Symfony/3.X"
]
"accept" => array:1 [
0 => "application/json"
]
"accept-language" => array:1 [
0 => "en-us,en;q=0.5"
]
"accept-charset" => array:1 [
0 => "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
]
"content-type" => array:1 [
0 => "application/json"
]
"authorization" => array:1 [
0 => "Bearer abc"
]
"content-length" => array:1 [
0 => 2
] ] #cacheControl: [] }
以便您看到test中的标题传递给应用程序
答案 1 :(得分:0)
请检查您的身份验证卫士 也许是您的四方缓存请求,然后使用以前请求中的信息