How to test exceptions in PHPUnit?

Member

by adan , in category: PHP General , a year ago

How to test exceptions in PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a year ago

@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. First, write a test method in your PHPUnit test class:
 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);
}


  1. The expectException() method expects the fully qualified name of the exception class. In the example above, we are expecting a DivisionByZeroError exception to be thrown.
  2. Use the expectExceptionMessage() method to verify that the correct exception message is thrown. This step is optional but recommended to ensure that the exception contains the expected error message.
  3. Finally, call the method that is expected to throw the exception within the test method. In the example above, we call the divide() method of a Calculator class that throws a DivisionByZeroError exception when dividing by 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.