Php 如何在Laravel测试未经授权的方法?

Php 如何在Laravel测试未经授权的方法?,php,laravel,laravel-5,php-7,Php,Laravel,Laravel 5,Php 7,我有控制器Post和典型的CRUD方法。 我有一个后政策,其中: public function destroy(User $user, Post $post) { $user->id === $post->author_id; } 我想为此编写测试。当我检查用户是否删除他自己的帖子时,一切正常 但当我测试其他用户是否可以删除自己的帖子时,laravel测试发送错误: Illuminate\Auth\Access\AuthorizationException: This a

我有控制器
Post
和典型的CRUD方法。 我有一个后政策,其中:

public function destroy(User $user, Post $post)
{
    $user->id === $post->author_id;
}
我想为此编写测试。当我检查用户是否删除他自己的帖子时,一切正常

但当我测试其他用户是否可以删除自己的帖子时,laravel测试发送错误:

Illuminate\Auth\Access\AuthorizationException: This action is unauthorized.
如何绕过它,或者哪个有其他方法来编写此测试

代码


您可以在测试方法的开头添加以下内容:

$this->expectException(\Illuminate\Auth\Access\AuthorizationException::class);

编辑

您的测试方法可能类似于:

/** @test */
function a_user_can_delete_their_own_post()
{
    $user = factory(User::class)->create();

    $post = factory(Post::class)->create([
        'editor_id' => $user->id,
    ]);

    $this->actingAs($user);

    $this
        ->delete("/api/feeds/{$post->id}", [], [
            'authorization' => "Bearer {$user->api_token}",
            'accept'        => 'application/json',
        ])
        ->assertResponseOk();

    $this->assertFalse(Post::where('id', $post->id)->exists());
}

/** @test */
function a_user_can_not_delete_a_post_they_do_not_own()
{
    $this->expectException(\Illuminate\Auth\Access\AuthorizationException::class);

    $user = factory(User::class)->create();

    $post = factory(Post::class)->create([
        'editor_id' => $user->id + 1,
    ]);

    $this->actingAs($user);

    $this->delete("/api/feeds/{$post->id}", [], [
        'authorization' => "Bearer {$user->api_token}",
        'accept'        => 'application/json',
    ]);
}

希望这有帮助

你能为你的测试显示代码吗?更新帖子…你使用的是什么版本的Laravel 5?测试将始终完成,即使用户也不能删除帖子。当我添加你编写的字符串时-test总是OK,所以我没有预料到结果。@yrrtyrt您是否在测试一个用户可以删除一篇文章,而另一个用户不能用相同的方法(函数)删除一篇文章?我测试user1是否可以删除自己的post1,user2是否可以删除user1的post1。@yrrtyrt您能否将整个测试方法添加到您的问题中(包括
函数
部分)?
/** @test */
function a_user_can_delete_their_own_post()
{
    $user = factory(User::class)->create();

    $post = factory(Post::class)->create([
        'editor_id' => $user->id,
    ]);

    $this->actingAs($user);

    $this
        ->delete("/api/feeds/{$post->id}", [], [
            'authorization' => "Bearer {$user->api_token}",
            'accept'        => 'application/json',
        ])
        ->assertResponseOk();

    $this->assertFalse(Post::where('id', $post->id)->exists());
}

/** @test */
function a_user_can_not_delete_a_post_they_do_not_own()
{
    $this->expectException(\Illuminate\Auth\Access\AuthorizationException::class);

    $user = factory(User::class)->create();

    $post = factory(Post::class)->create([
        'editor_id' => $user->id + 1,
    ]);

    $this->actingAs($user);

    $this->delete("/api/feeds/{$post->id}", [], [
        'authorization' => "Bearer {$user->api_token}",
        'accept'        => 'application/json',
    ]);
}