0

Here is a custom exception

namespace App\Exceptions;

use Exception;

class CustomException extends Exception
{
    public function render($request)
    {
        return response()->view('custom-exception');
    }
}

I throw it inside a Request class

class LoginRequest extends FormRequest
{
    public function authenticate()
    {
        if (! Auth::attempt($this->only('email', 'password'))) {
            throw CustomException(); //
        }
    }
}

This is the controller which call the LoginRequest class

class AuthenticatedSessionController extends Controller
{
    public function store(LoginRequest $request) //
    {
        $request->authenticateMember();

        $request->session()->regenerate();

        return redirect()->intended(RouteServiceProvider::Home);
    }
}

This is the test

use Tests\TestCase;
use App\Models\User;
use App\Exceptions\CustomException;

class EmailVerificationTest extends TestCase
{
    public function test_email_verification_screen_can_be_rendered()
    {
        $user = User::factory()->create([
            'email_verified_at' => null,
        ]);

        // $this->expectException(CustomException::class); //this cannot pass

        $response = $this->post(
            '/login',
            [
                'email' => 'john@example.com',
                'password' => 'secret'
            ]
        );

        $response->assertViewIs('custom-exception');

        $this->assertInstanceOf(CustomException::class, $response->exception);
    }
}    

These assertions can pass:

$response->assertViewIs('custom-exception');

$this->assertInstanceOf(CustomException::class, $response->exception);

But this one cannot pass:

$this->expectException(CustomException::class);

Failed asserting that exception of type "App\Exceptions\CustomException" is thrown.

Why? Any idea?

Autodesk
  • 631
  • 8
  • 27
  • 1
    It will not work because you are handling the exception, you are literally rendering the exception so you are handling it, your test is right (without the `expectException` but with `assertViewIs` and `assertInstanceOf`). `expectException` will only work when you are never handling the exception and the final error is literally throwing the exception and no one catches it – matiaslauriti Jun 08 '22 at 15:28

1 Answers1

-1

The method expectException() will only work when the exception thrown is not handled.

Please add the below line in your function

$this->withoutExceptionHandling();

then this method expectException() will work.

  • 1
    Don't add that method at the exception **IS** being handled... @Autodesk you are handling the method, you are literally showing a VIEW, so you are handling the exception, so `expectException` will never work... – matiaslauriti Jun 08 '22 at 15:28