'Laravel phpunit unauthorized test return exeption insted of response

I make a simple controller function test, with user has no permission for this action, thet should abort with 403 unauthorized.

test:

    public function setUp(): void
    {
        parent::setUp();

        $user = User::factory()
            ->create([
                'email' => '[email protected]',
        ]);

        $this->token = JWTAuth::fromUser($user);

        JWTAuth::setToken($this->token);

        $this->withHeaders([
            'Accept' => 'application/json',
            'Authorization' => 'Bearer ' . $this->token,
        ]);
    }

    /** @test */
    public function shouldDenieListAsUnauthorizedUser(): void
    {
        $this->get(action([$this->controller, 'list']))
            ->assertStatus(403);
    }

In the custom request php file in authenticate function work fine, the gate return with false. But the test fail because get exeption instead of 403 code. enter image description here

the formrequest auth function:

    public function authorize()
    {
        return Gate::allows('viewAny-tag');
    }

the code work fine, but the test fail. I don't know why.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source