Want to check the exception thrown correctly by PHPUnit? 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 an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | /** * @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); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.