Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use expectException in PHPUnit?

I'm trying to test my Exception, or any other exception in PHP Unit.

<?php declare(strict_types=1);


namespace Tests\Exception;

use PHPUnit\Framework\TestCase;

class DrinkIsInvalidExceptionTest extends TestCase
{
    public function testIsExceptionThrown(): void
    {
        $this->expectException(\Exception::class);
        try {
            throw new \Exception('Wrong exception');
        } catch(\Exception $exception) {
            echo $exception->getCode();
        }

    }

}

Still fails:

Failed asserting that exception of type "Exception" is thrown.

What could be the problem?

like image 785
Grzegorz Pietrzak Avatar asked Jun 13 '26 00:06

Grzegorz Pietrzak


1 Answers

The problem is that the exception is never thrown because you are catching it in the catch block. The correct code to test your exception would be this:

class DrinkIsInvalidExceptionTest extends TestCase
{
    public function testIsExceptionThrown(): void
    {
        $this->expectException(\Exception::class);
        $this->expectExceptionCode('the_expected_code');
        $this->expectExceptionMessage('Wrong exception');

        // Here the method that throws the exception
        throw new \Exception('Wrong exception');
    }
}
like image 82
Pablo LaVegui Avatar answered Jun 14 '26 13:06

Pablo LaVegui