Search code examples
phperror-handlingphpunitassertexpected-exception

How to assert Errors instead of Exception in phpunit?


In my unit test I want to caught if an ArithmeticError has been thrown, just like for an Exception using the @expectedException tag.

Unfortunally, it seems that phpunit recognize only Exceptions and not Errors.

Anyone know how to test for expected errors, instead excpetions?


Solution

  • Found the solution. Using error_reporting(2); in a TestCase's setUp method ensure phpunit can convert all Errors in Exceptions. I tried various error reporting levels, but only the one above works (see the error reporting levels). In this case was simple to me:

    class DivisionTest extends TestCase
    {
      public function setUp() : void
      {
        $this->division = new Division;
        error_reporting(2);
      }
    
      /**
       * When divide by zero (x / 0) should throw an Error.
       * @expectedException DivisionByZeroError
       */
      public function testDivedByZeroThrowException()
      {
        // Act
        $result = $this->division->run(0, 5); // 5 : 0
      }
    }
    

    Now this test returns Success!!! For more information visit Testing PHP Errors.