8

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?

1
  • Came looking for a solution to this issue as well. I haven't found any great documentation on this. If I try the solution from Pablo (which looks valid) I still get an exception thrown. If I put the expectException inside of the catch of a try-catch, the exception is caught, but it still outputs an error message during my test run. Commented Dec 15, 2020 at 1:51

1 Answer 1

16

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');
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.