PHPUnit assert that an exception was thrown?

Does anyone know whether there is an assert or something like that which can test whether an exception was thrown in the code being tested?

2 Likes
<?php
require_once 'PHPUnit/Framework.php';

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        $this->expectException(InvalidArgumentException::class);
        // or for PHPUnit < 5.2
        // $this->setExpectedException(InvalidArgumentException::class);

        //...and then add your test code that generates the exception 
        exampleMethod($anInvalidArgument);
    }
}

expectException() PHPUnit documentation

PHPUnit author article provides detailed explanation on testing exceptions best practices.

Refer: https://stackoverflow.com/questions/5683592/phpunit-assert-that-an-exception-was-thrown

2 Likes