Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit doesn't catch expected exceptions

I have a set of tests, and I want to test that my classes throw exceptions at the right time. In the example, my class uses the __get() magic method, so I need to test that an exception is thrown when an invalid property is retrieved:

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 isn't caught!

There was 1 error:

1) QueryTest::testExceptionThrownWhenGettingInvalidProperty
Exception: Property qwerty does not exist

I was using SimpleTest before, and $this->expectException(new Exception("Property qwerty does not exist")); worked just 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?

like image 446
Nathan MacInnes Avatar asked Nov 11 '10 20:11

Nathan MacInnes


1 Answers

It's not looking for the text in the exception, it's looking for the name of the exception class... Docs

$this->setExpectedException('Exception');

It's quite handy when you're using SPL Exceptions, or custom exception classes...

like image 52
ircmaxell Avatar answered Oct 04 '22 14:10

ircmaxell