Test exceptions
suggest changeLet’s say you want to test a method which throws an exception
class Car
{
/**
* @throws \Exception
*/
public function drive()
{
throw new \Exception('Useful message', 1);
}
}
You can do that by enclosing the method call in a try/catch block and making assertions on the exception object’s properties, but more conveniently you can use exception assertion methods. As of PHPUnit 5.2 you have expectException(), expectExceptionMessage(), and expectExceptionCode() for asserting exception type, message, and code. PHPUnit 6 removed PHPUnit_Framework_TestCase; later versions extend PHPUnit\Framework\TestCase.
class DriveTest extends PHPUnit\Framework\TestCase
{
public function testDrive()
{
// prepare
$car = new \Car();
$expectedClass = \Exception::class;
$expectedMessage = 'Useful message';
$expectedCode = 1;
// test
$this->expectException($expectedClass);
$this->expectExceptionMessage($expectedMessage);
$this->expectExceptionCode($expectedCode);
// invoke
$car->drive();
}
}
If you are using an earlier version of PHPUnit, setExpectedException() can be used instead of those methods, but keep in mind that it is deprecated and PHPUnit 6 removes it together with PHPUnit_Framework_TestCase.
class DriveTest extends PHPUnit_Framework_TestCase
{
public function testDrive()
{
// prepare
$car = new \Car();
$expectedClass = \Exception::class;
$expectedMessage = 'Useful message';
$expectedCode = 1;
// test
$this->setExpectedException($expectedClass, $expectedMessage, $expectedCode);
// invoke
$car->drive();
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents