如何使用Passport在

时间:2018-09-28 13:36:28

标签: php laravel phpunit laravel-5.6

我正在尝试编写一个首先对用户进行身份验证的PHPUnit测试,然后再允许用户发出发布请求但出现错误

  

1)测试\功能\图书测试:: test_onlyAuthenticatedUserCanAddBook成功   ErrorException:尝试获取非对象的属性“ client”

     

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测试,我不知道为什么会收到此错误。我该如何运作?

1 个答案:

答案 0 :(得分:3)

您可以使用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);
}

在此处查看文档-https://laravel.com/docs/5.7/passport#testing