PHPUnit assert that an exception was thrown? PHPUnit assert that an exception was thrown? php php

PHPUnit assert that an exception was thrown?


<?phprequire_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.


You can also use a docblock annotation until PHPUnit 9 is released:

class ExceptionTest extends PHPUnit_Framework_TestCase{    /**     * @expectedException InvalidArgumentException     */    public function testException()    {        ...    }}

For PHP 5.5+ (especially with namespaced code), I now prefer using ::class


If you're running on PHP 5.5+, you can use ::class resolution to obtain the name of the class with expectException/setExpectedException. This provides several benefits:

  • The name will be fully-qualified with its namespace (if any).
  • It resolves to a string so it will work with any version of PHPUnit.
  • You get code-completion in your IDE.
  • The PHP compiler will emit an error if you mistype the class name.

Example:

namespace \My\Cool\Package;class AuthTest extends \PHPUnit_Framework_TestCase{    public function testLoginFailsForWrongPassword()    {        $this->expectException(WrongPasswordException::class);        Auth::login('Bob', 'wrong');    }}

PHP compiles

WrongPasswordException::class

into

"\My\Cool\Package\WrongPasswordException"

without PHPUnit being the wiser.

Note: PHPUnit 5.2 introduced expectException as a replacement for setExpectedException.