@expectedExceptionCode

@expectedExceptionCode

The @expectedExceptionCode annotation, in conjunction with the @expectedException allows making assertions on the error code of a thrown exception thus being able to narrow down a specific exception.

use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    /**
     * @expectedException     MyException
     * @expectedExceptionCode 20
     */
    public function testExceptionHasErrorcode20()
    {
        throw new MyException('Some Message', 20);
    }
}

To ease testing and reduce duplication a shortcut can be used to specify a class constant as an @expectedExceptionCode using the "@expectedExceptionCode ClassName::CONST" syntax.

use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    /**
      * @expectedException     MyException
      * @expectedExceptionCode MyClass::ERRORCODE
      */
    public function testExceptionHasErrorcode20()
    {
      throw new MyException('Some Message', 20);
    }
}
class MyClass
{
    const ERRORCODE = 20;
}
doc_PHPUnit
2016-10-16 15:37:30
Comments
Leave a Comment

Please login to continue.