如何在phpunit中添加授权标头?我正在测试一个需要api_token的json api。 laravel docs提供了一个代理方法。但是这在我的情况下不起作用,因为api令牌与users表没有直接关系。
编辑:
public function test_returns_response_with_valid_request()
{
$response = $this->json('post', '/api/lookup', [
'email' => 'user@gmail.com'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
答案 0 :(得分:10)
您还可以通过将保护名称作为第二个参数传递给
actingAs
方法来指定应该使用哪个保护来验证给定用户:$this->actingAs($user, 'api');
答案 1 :(得分:4)
您可以使用withHeader方法并传递令牌,这对我的本地系统(Laravel 6)有效
public function test_returns_response_with_valid_request()
{
// define your $token here
$response = $this->withHeader('Authorization', 'Bearer ' . $token)
->json('post', '/api/lookup', [
'email' => 'user@gmail.com'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
或者您可以在带有API保护的docs here中使用actingAs
public function test_returns_response_with_valid_request()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user, 'api')
->json('post', '/api/lookup', [
'email' => 'user@gmail.com'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
答案 2 :(得分:0)
public function test_returns_response_with_valid_request()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->post('/api/lookup',[
'email' => 'user@gmail.com'
]);
$response->assertStatus(200);
$response->assertJsonStructure([
'info' => [
'name'
]
]);
}
答案 3 :(得分:0)
根据本文档 https://laravel.com/docs/5.8/api-authentication#passing-tokens-in-requests & https://laravel.com/docs/8.x/http-tests
有多种方法可以将 API 令牌传递到您的应用程序。 您可以根据应用程序的需要选择其中任何一种方法。
$response = $this->json('POST', '/api/sth?api_token='.$token, $test_data)->assertSussessful();
$response = $this->json('GET', '/api/sth', [
'headers' => [
'Accept' => 'application/json',
],
'form_params' => [
'api_token' => $token,
],
]);
$response = $this->json('GET', '/api/sth', [
'headers' => [
'Authorization' => 'Bearer '. $token,
'Accept' => 'application/json'
]
]);
$response = $this->withHeaders([
'Authorization' => 'Bearer '. $token,
'Accept' => 'application/json'
])->post('/api/sth', $test_data);