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

时间:2015-12-18 11:19:51

标签: php testing http-headers phpunit

我正在尝试使用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());

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

4 个答案:

答案 0 :(得分:3)

有一个将标题转换为服务器变量的功能。尝试传递这个:

$this->transformHeadersToServerVars([ 'Authorization' => $token ])

答案 1 :(得分:0)

$server参数是服务器变量的数组,而不是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
]);

答案 2 :(得分:0)

只是猜测......

检查你的.htaccess,它必须包含

RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

答案 3 :(得分:-1)

我正在使用PHP单元进行一些功能测试。

$client->request('GET','url', [], [], ['HTTP_Authorization' => $token]);

对我有用!