如何使用 Passport 在 phpunit 测试中验证用户
How can I authenticate users in phpunit Testing using Passport
我正在尝试编写一个 PHPUnit 测试,在允许用户发出 post 请求之前先对用户进行身份验证,但出现错误
1) Tests\Feature\BooksTest::test_onlyAuthenticatedUserCanAddBookSuccessfully
ErrorException: Trying to get property 'client' of non-object
C:\wamp64\www\bookstore\vendor\laravel\passport\src\ClientRepository.php:89
C:\wamp64\www\bookstore\vendor\laravel\passport\src\PersonalAccessTokenFactory.php:71
C:\wamp64\www\bookstore\vendor\laravel\passport\src\HasApiTokens.php:67
C:\wamp64\www\bookstore\tests\Feature\BooksTest.php:20
当我 运行 我的 BooksTest
public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
{
$user = factory(User::class)->create();
$token = $user->createToken('bookbook')->accessToken;
$response = $this->withHeaders(['Authorization' => 'Bearer '.$token])
->json('POST', '/api/books', [
'title' => 'new book post',
'author' => 'new author',
'user_id' => $user->id
]);
$response->assertStatus(201);
}
这是我第一次使用 PHPUnit 测试,我不知道为什么会出现此错误。我如何让它发挥作用?
您可以使用 Passport::actingAs
来完成此操作。
例如:
public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
{
$user = factory(User::class)->create();
Passport::actingAs($user);
$response = $this->json('POST', '/api/books', [
'title' => 'new book post',
'author' => 'new author',
'user_id' => $user->id
]);
$response->assertStatus(201);
}
我正在尝试编写一个 PHPUnit 测试,在允许用户发出 post 请求之前先对用户进行身份验证,但出现错误
1) Tests\Feature\BooksTest::test_onlyAuthenticatedUserCanAddBookSuccessfully ErrorException: Trying to get property 'client' of non-object
C:\wamp64\www\bookstore\vendor\laravel\passport\src\ClientRepository.php:89 C:\wamp64\www\bookstore\vendor\laravel\passport\src\PersonalAccessTokenFactory.php:71 C:\wamp64\www\bookstore\vendor\laravel\passport\src\HasApiTokens.php:67 C:\wamp64\www\bookstore\tests\Feature\BooksTest.php:20
当我 运行 我的 BooksTest
public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
{
$user = factory(User::class)->create();
$token = $user->createToken('bookbook')->accessToken;
$response = $this->withHeaders(['Authorization' => 'Bearer '.$token])
->json('POST', '/api/books', [
'title' => 'new book post',
'author' => 'new author',
'user_id' => $user->id
]);
$response->assertStatus(201);
}
这是我第一次使用 PHPUnit 测试,我不知道为什么会出现此错误。我如何让它发挥作用?
您可以使用 Passport::actingAs
来完成此操作。
例如:
public function test_onlyAuthenticatedUserCanAddBookSuccessfully()
{
$user = factory(User::class)->create();
Passport::actingAs($user);
$response = $this->json('POST', '/api/books', [
'title' => 'new book post',
'author' => 'new author',
'user_id' => $user->id
]);
$response->assertStatus(201);
}