使用api令牌认证的laravel phpunit测试

Chr*_*ris 5 phpunit laravel

如何在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'
            ]
        ]);
    }
Run Code Online (Sandbox Code Playgroud)

小智 16

根据文件.

您还可以通过将保护名称作为第二个参数传递给方法来指定应该使用哪个保护来验证给定用户actingAs:

$this->actingAs($user, 'api');
Run Code Online (Sandbox Code Playgroud)


Tom*_*hil 6

您可以使用 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'
        ]
    ]);
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用actingAs查看文档here with api guard

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'
        ]
    ]);
}
Run Code Online (Sandbox Code Playgroud)


小智 1

根据文件

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'
             ]
         ]);
}
Run Code Online (Sandbox Code Playgroud)