To test exceptions and error conditions in PHPUnit, you can use the expectException()
and expectExceptionMessage()
methods.
Here's an example of how you can test for an exception:
PHPUnit\Framework\TestCase
.use PHPUnit\Framework\TestCase;
class MyTestClass extends TestCase
{
// Your test methods go here
}
expectException()
method and pass the expected exception class as a parameter.public function testMyMethod()
{
$this->expectException(MyException::class);
// Call the method that should throw the exception
MyTestClass::myMethod();
}
expectExceptionMessage()
method.public function testMyMethod()
{
$this->expectException(MyException::class);
$this->expectExceptionMessage('This is the expected exception message');
// Call the method that should throw the exception
MyTestClass::myMethod();
}
These methods enable you to ensure that your code correctly throws exceptions in response to specific conditions, allowing you to validate error handling and propagation.