PHPUnit does not catch expected exceptions

I have a test suite, and I want to check that my classes throw exceptions at the right time. In this example, my class uses the __get () magic method, so I need to check if an exception occurs when I get an invalid property:

function testExceptionThrownWhenGettingInvalidProperty() { $obj = new MyClass(); $this->setExpectedException("Property qwerty does not exist"); $qwerty = $obj->qwerty; } 

The class throws an error as it should, but instead of just getting a pass, the exception is not caught!

 There was 1 error: 1) QueryTest::testExceptionThrownWhenGettingInvalidProperty Exception: Property qwerty does not exist 

I used SimpleTest before, and $this->expectException(new Exception("Property qwerty does not exist")); worked fine. I know there are other methods (@expectedException and try-catch), but this one should work and it looks a lot cleaner. Any ideas how I can make this work?

+6
php exception unit-testing phpunit
source share
2 answers

It is not looking for text in the exception, it is looking for the name of the exception class ... Documents

 $this->setExpectedException('Exception'); 

This is very convenient if you use SPL Exceptions or custom exception classes ...

+13
source share

Adding ircmaxell to the answer, there is actually an easier way to do this:

 /** * @expectedException MyExceptionClass * @expectedExceptionMessage Array too small */ public function testSomething() { } 

@expectedException the class name of the expected exception, and @expectedExceptionMessage is the substring of the waiting exception message (this right is not necessary for the entire message).

If you prefer not to use docblock annotations, they are both available as methods in the test case.

+13
source share

All Articles