Search code examples
phpexceptionphpunittestcase

How to check the exception thrown correctly by PHPUnit?


I have div() in Cal class in my CalTest class has following methods to test the div().

public fucnction div($a,$b){
   if($b == 0){
    throw new Exception("Divided by zero");
   }
   return $a/$b
}

I can pass only testDiv() but testDiv2().

enter image description here

I want to catch check wheather the exeption thrown correctly using PHPUnit. What am I missing here?? Your help is highly appreciated. Thank you!

enter image description here


Solution

  • Just came across the same issue. For some reason PHPUnit will not allow you to set the expectedException to a generic exception and I am not sure why. Personally I opt to throw custom Exception codes rather than have to create a new exception class every time I want to differentiate exceptions.

    Here is how I got around it:

    /**
     * @expectedException Test_Exception
     */
    public function testDivByZero()
    {
        try {
            // Fyi you don't need to do an assert test here, as we are only testing the exception, so just make the call
            $result = $this->object->div(1,0);
        } catch (Exception $e) {
            if ('Exception' === get_class($e)) {
                throw new Test_Exception($e->getMessage(), $e->getCode());
            }
        }
     }
    
     // Test_Exception.php
     class Test_Exception extends Exception
     {
         public function __construct($message = null, $code = 0, Exception $previous = null)
         {
             parent::__construct($message, $code, $previous);
         }
     }
    

    This will allow you to engineer your code the way you want, and throw "generic" exceptions. Basically it just tests the Exception class and if it's generic, re-wrap it as a different exception; Test_Exception.

    -- Update --

    Found out yesterday that they have removed the generic exception restriction in the current "master" branch, which will be 3.7. Apparently the lead engineer has no desire of patching 3.6.