Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yoeriboven's avatar

ExpectException() doesn't work when it is catched

Here's my (simplified) code:

/** @test */
public function it_throws_an_exception()
{
    $this->withoutExceptionHandling();
    
    $this->expectException(PrivateProfileException::class);

    $this->post('/', []);
}

public function store(Request $request) {
    try {
        throw new PrivateProfileException();
    } catch (PrivateProfileException $e) {
        dd('The profile is private');
    }
}

The test fails every time and runs the catch block. When I remove the catch block the test succeeds.

How do I get the exception with the test, but catch it when accessing through the browser?

More info: When I remove the catch block and $this->withoutExceptionHandling() the test fails and shows this:

Failed asserting that exception of type "App\Exceptions\PrivateProfileException" is thrown.
0 likes
2 replies
Talinon's avatar

expectException() will only return true if the exception thrown is not handled. In your case, since you catch it immediately, the test faIls.

Either change your store method to throw your exception without catching it, or go about your test in a different way.

I realize in this example you're just doing some trial and error, but what exactly do you want to test? What I gather, you don't want to allow Private Profiles to be able to hit the store method.

So - maybe you want to place that logic in middleware, and then test that the user gets denied.

Something like:

public function private_profiles_may_not_create_whatever() 
{

    $this->actingAs($privateProfileUser)->post('/', [])
        ->assertStatus(401);

}
1 like
tobz.nz's avatar

I had the same issue. You can call $this->withoutExceptionHandling(); first and it works as expected.

1 like

Please or to participate in this conversation.