@adan
To test exceptions in PHPUnit, you can use the expectException()
and expectExceptionMessage()
methods provided by PHPUnit's TestCase
class. Here's an example of how to test an exception using these methods:
1 2 3 4 5 6 7 8 9 10 11 12 |
public function testException() { // Arrange $calculator = new Calculator(); // Act & Assert $this->expectException(DivisionByZeroError::class); $this->expectExceptionMessage('Division by zero is not allowed.'); // calling a method that throws an exception $calculator->divide(10, 0); } |
When running PHPUnit, it will assert that the expected exception is thrown with the expected message. If the exception is not thrown or the message doesn't match, the test will fail.
Note: Make sure that the method throwing the exception is not caught and handled in any way, as PHPUnit relies on the exception bubbling up to its test runner for verification.
Remember to replace Calculator
with the actual class you want to test, and DivisionByZeroError
with the appropriate exception class you expect to be thrown.