Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I authenticate users in phpunit Testing using Passport

I am trying to write a PHPUnit test that authenticates a user first before allowing the user to make a post request but got the error

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

When I run my 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);
}

It's my first time working with PHPUnit test, and I have no idea why I'm getting this error. How do I make it work?

like image 425
Mena Avatar asked Jun 11 '26 05:06

Mena


1 Answers

You can use Passport::actingAs to accomplish this.

For example:

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);
}

See the documentation here - https://laravel.com/docs/5.7/passport#testing


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!