我正在尝试编写一个首先对用户进行身份验证的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测试,我不知道为什么会收到此错误。我该如何运作?
答案 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);
}