PHPUnit 没有捕获预期的异常

2024-03-25

我有一组测试,我想测试我的类是否在正确的时间抛出异常。在示例中,我的类使用 __get() 魔术方法,因此我需要测试检索无效属性时是否引发异常:

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

该类按其应有的方式抛出错误,但不仅没有获得通过,还没有捕获异常!

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),但是这个应该可以工作,而且看起来干净多了。我有什么想法可以让这项工作成功吗?


它不是在寻找异常中的文本,而是在寻找异常类的名称......Docs http://www.phpunit.de/manual/3.2/en/writing-tests-for-phpunit.html

$this->setExpectedException('Exception');

使用的时候还是蛮方便的声压级例外 https://www.php.net/manual/en/spl.exceptions.php,或自定义异常类...

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

PHPUnit 没有捕获预期的异常 的相关文章

随机推荐