PHPUnit assert that an exception was thrown?

Felipe picture Felipe · Apr 16, 2011 · Viewed 214.9k times · Source

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?

Answer

Frank Farmer picture Frank Farmer · Apr 16, 2011
<?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.