3

我在测试 Laravel 5.5 时遇到问题。我需要在 TEST HEADER 中发送不记名令牌,但不起作用

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
            ]
          ]

我的标题没有出现。我认为我是对的

4

2 回答 2

9

您在此处设置的标头显然是针对请求的,对于响应您从 Laravel 应用程序获取标头,因此显然您不会看到为请求设置的标头。

如果您想查看您在此处设置的标头,您应该dd($request);在您的应用程序中运行,而不是在测试中运行。

编辑

要确认标头已传递给应用程序,整个测试代码:

测试/功能/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: [] }

所以你看到来自测试的标题被传递给应用程序

于 2017-11-21T19:19:18.457 回答
0

请检查您的 Auth 守卫 也许您的 auth quard 缓存请求,而不是使用先前请求中的信息

于 2020-11-09T10:10:55.877 回答