PHPUnit没有捕获预期的异常 [英] PHPUnit doesn't catch expected exceptions
问题描述
我有一组测试,我想测试我的类在正确的时间抛出异常.在示例中,我的类使用__get()魔术方法,因此我需要测试是否在检索到无效属性时引发了异常:
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
我以前使用过SimpleTest,并且$this->expectException(new Exception("Property qwerty does not exist"));
正常工作.我知道还有其他方法(@expectedException和try-catch),但是这种方法应该可以工作,而且看起来更干净.有什么想法可以使我工作吗?
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?
推荐答案
It's not looking for the text in the exception, it's looking for the name of the exception class... Docs
$this->setExpectedException('Exception');
当您使用 SPL异常时,这非常方便自定义异常类...
It's quite handy when you're using SPL Exceptions, or custom exception classes...
这篇关于PHPUnit没有捕获预期的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!