PHPUnit Testing Exceptions

There are two ways to tell PHPUnit that you wish to test that an exception was thrown, when you tried to execute your code. It is a good practice to write meaningful names describing which exception was been thrown.

Using the expectException() method

use PHPUnit\Framework\TestCase;
use InvalidArgumentException;

class ModelTest extends TestCase
{
    public function testInvalidArgumentExceptionWasThrown()
    {
        $this->expectException(InvalidArgumentException::class);
    }
}

Using the @expectedException annotation

use PHPUnit\Framework\TestCase;
use InvalidArgumentException;

class ModelTest extends TestCase
{
    /**
     * @expectedException InvalidArgumentException
     */
    public function testInvalidArgumentExceptionWasThrown()
    {
        // your code in here
    }
}
what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.