如何使用phpunit api请求发送标头?

Roh*_*han 5 php testing phpunit http-headers

我正在尝试使用 phpunit 测试我在 laravel 5 中编写的 Web 服务。我是这个测试框架的新手。应用程序使用 JWT 进行身份验证,该身份验证在请求的标头中传递。

我的测试看起来像这样:

$response = $this->call('POST', 'authenticate', [
    'username' => 'carparts',
    'email' => 'admin@admin.com',
    'password' => 'password'
]);

$token = 'Bearer ' . json_decode($response->getContent())->token;

$response = $this->call('POST', 'users', [
    "first_name"    => "Test",
    "last_name"     => "Test",
    "email"         => 'test@test.com',
    "password"      => "testing",
    "role"          => "1"
], [], [], [
    'Authorization' => $token
]);

dd($response->getContent());
Run Code Online (Sandbox Code Playgroud)

令牌返回正常,但是当我尝试在下一个请求中使用以创建新用户时,它失败说无法从请求中解析令牌。当我request()->headers在中间件中做检查时,即使是这样也不显示标题。我究竟做错了什么?如何使用 PHPUnit 在请求中传递标头?

Ale*_*lex 0

$serverargument 是服务器变量数组,而不是 http 标头。
将您的令牌传递为HTTP_AUTHORIZATION

$response = $this->call('POST', 'users', [
    "first_name"    => "Test",
    "last_name"     => "Test",
    "email"         => 'test@test.com',
    "password"      => "testing",
    "role"          => "1"
], [], [], [
    'HTTP_AUTHORIZATION' => $token
]);
Run Code Online (Sandbox Code Playgroud)