如何在laravel中使用php单元进行注销测试?

t9aqgxwy  于 2023-03-28  发布在  PHP
关注(0)|答案(1)|浏览(101)

我构建了以下方法,但它给我的状态错误为500,而不是200。

public function test_logout_success()
{
    $user = User::factory()->create();
    $role = Role::findByName('admin', 'api');
    $user->assignRole($role);

    Passport::actingAs($user,'api');

    $token = $user->createToken(config('create-token'))->accessToken;

    $user->save();

    $this->get('/logout', [
        'Authorization' => 'Bearer ' . $token,
    ])->assertStatus(200);
}

我真的不知道我做错了什么,真的,任何帮助?谢谢。
我尝试按如下方式登录:

$requestData = [
    'email' => $user->email,
    'password' => 'P@ssword'
];
        
$response = $this->actingAs($user)->post('/login', $requestData);

要稍后从响应中获取令牌,请使用:

$response->json('data.token')

这次我收到了一个403。
但它也不起作用,我不清楚用户是否仍然真诚地登录。

public function test_logout_success()
{
    $user = User::factory()->create();
    $role = Role::findByName('admin', 'api');
    $user->assignRole($role);
    
    $requestData = [
        'email' => $user->email,
        'password' => 'P@ssword'
    ];
    
    $response = $this->actingAs($user)->post('/api/v1/auth/login', $requestData);
    
    $this->get('/api/v1/auth/logout', [
        'Authorization' => 'Bearer ' . $response->json('data.token'),
    ])->assertStatus(200);
}
unhi4e5o

unhi4e5o1#

我马上发现你提要求的方式有问题:Authorization: Bearer ...是一个标头。您将其作为数据传递。
试着像这样提出你的请求:

$response = $this->withHeaders(['Authorization' => 'Bearer ' . $token])->get('/logout');

$response->assertStatus(200);

然后,为了Assert您已经注销,您可以使用assertGuest($guard = null)因为您使用的是API,我假设在这种情况下的保护是api(检查您的config/auth.php文件)。

public function test_logout_success()
{
    // ARRANGE
    /**
     * create user
     * log it in
     * make sure it's logged in with the api guard by writing a pre-assertion
     */
    $this->assertAuthenticated('api');

    // ACT
    /**
     * hit the logout endpoint
     */
    $response = $this->withHeaders(['Authorization' => 'Bearer ' . $token])->get('/logout');

    // ASSERT
    /**
     * make sure the server responds with a successful http status
     * and user has been logged out of the api guard
     */
    $response->assertStatus(200);
    $this->assertGuest('api');
}
  • https://laravel.com/docs/10.x/http-tests#customizing-request-headers
  • https://laravel.com/docs/10.x/http-tests#authentication-assertions

相关问题