dskvfdxgdo2422392
2018-09-28 13:36
浏览 165
已采纳

如何使用Passport在phpunit测试中验证用户身份

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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试编写一个PHPUnit测试,在允许用户发出帖子请求之前先对用户进行身份验证 错误

1)Tests \ Feature \ BooksTest :: test_onlyAuthenticatedUserCanAddBookSuccessfully ErrorException:尝试获取非对象的属性“client” \ n

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时

 公共函数test_onlyAuthenticatedUserCanAddBookSuccessfully()
 {
 $ user = factory(User :: class)  - > create(); 
 $ token = $ user-> createToken('bookbook') - > accessToken; 
 
 $ response = $ this-> withHeaders(['Authorization'=>'  Bearer'。$ token])
  - > json('POST','/ api / books',[
'title'=>  '新书帖',
'作者'=>  '新作者',
'user_id'=>  $ user-> id 
]); 
 
 $ response-> assertStatus(201); 
} 
   
 
 

这是我第一次工作 使用PHPUnit测试,我不知道为什么我会收到此错误。 我如何使它工作?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyanghan0556 2018-09-28 13:59
    已采纳

    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

    打赏 评论

相关推荐 更多相似问题