Search code examples
laravellaravel-testinglaravel-exceptions

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 : 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 ?


Solution

  • 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.