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

时间:2017-08-30 10:56:18

标签: php laravel laravel-5 php-7

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

public function destroy(User $user, Post $post)
{
    $user->id === $post->author_id;
}

我想为此编写测试。当我检查用户是否删除自己的帖子时 - 一切OK。

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

Illuminate\Auth\Access\AuthorizationException: This action is unauthorized.

如何绕过它或者有另一种方法来编写这个测试?

代码

 <?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\Feeds\Feed;
use App\Models\User;
use Tests\SphinxConnection;
use Illuminate\Foundation\Testing\DatabaseMigrations;
class PolicyTest extends TestCase
{
    use DatabaseMigrations,
        SphinxConnection;

    public function testFeedPolicy()
    {
        $this->expectException(\Illuminate\Auth\Access\AuthorizationException::class);

        $user1 = factory(User::class)->create([
            'id' => 1,
        ]);
        $user2 = factory(User::class)->create([
            'id' => 2,
        ]);

        factory(Post::class)->create([
            'id' => 27,
            'editor_id' => 2,
        ]);
        factory(Post::class)->create([
            'id' => 30,
            'editor_id' => 2,
        ]);

        $this->delete('/api/feeds/27', [], [
            'authorization' => "Bearer {$user2->api_token}",
            'accept' => 'application/json',
        ])->assertJson([

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

        ]);;
    }
}

1 个答案:

答案 0 :(得分:0)

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

$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',
    ]);
}

希望这有帮助!