Summer Sale! All accounts are 50% off this week.

mstdmstd's avatar

How to checks raised exceptions in phpunit tests?

In laravel 9.26.1 app I make tests with phpunit ^9.5.10 and I want to make checks on raised exceptions on login with invalid credentials In app/Http/Requests/Auth/LoginRequest.php I see :

public function authenticate()
{
    $this->ensureIsNotRateLimited();
    if ( ! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
        RateLimiter::hit($this->throttleKey());

        throw ValidationException::withMessages([
            'email' => trans('auth.failed'),
        ]);
    }

I try to catch ValidationException and I found branch : https://stackoverflow.com/questions/38718513/testing-exceptions-in-phpunit

But adding code in my test :

public function testLoginWithFailure()
{
    ...
    $response->assertStatus(302);  // Redirection status
    $response->assertRedirect('/');
    $this->assertGuest();
    $this->expectException(ValidationException::class);

I got error in cosole running tests :

1) Tests\Feature\AuthTest::testLoginWithFailure
Failed asserting that exception of type "Illuminate\Validation\ValidationException" is thrown.

Here https://laravel.com/docs/9.x/http-tests I do not see any expectException method described...

How can I make checks on raised exceptions ?

0 likes
3 replies
Sinnbeck's avatar

Add $this->withoutExceptionHandling(); at the top of the method

1 like
mstdmstd's avatar

Yes, if I add in my tests

        $this->withoutExceptionHandling();

I got error :

1) Tests\Feature\AuthTest::testLoginWithFailure
Illuminate\Validation\ValidationException: These credentials do not match our records.
...

I suppose withoutExceptionHandlingis useful during tests debugging. But in this case AuthTest::testLoginWithFailure failed, but as I need to pass my tests I set

    ...
    $this->expectException(ValidationException::class);

I suppose this line would catch custom ValidationException in authenticate method ... But why it did not happen ?

mstdmstd's avatar
mstdmstd
OP
Best Answer
Level 8

I did not how method expectException can work, but calling method

$response->assertSessionHasErrors('email');

makes the same functionality I need and it salved my issue.

Please or to participate in this conversation.