我在我的代码中有这个
throw new Exception('need id and provider');
在phpunit测试中抛出这个错误:
Exception: need id and provider
当我这样做时:
$this->setExpectedException('need id and provider');
错误消失,但我得到这个:
ReflectionException: Class need id and provider不存在
我实际上是用一个错误换了另一个错误,没有回溯。
信息:
- 我不得不使用这个过时版本的PHP unit。
- 这是一个WordPress插件,我用我自己的测试构建在WP 5.6 PHPUnit测试。
- 这个错误在PHP 7.4.14上运行,但是我希望这个错误在我打算测试的所有其他版本上都能触发。
- 我读到一些关于
setExpectedException
被弃用的东西,不确定这是否与此有关。
我用:
$this->expectException('Exception');
它不会抛出关于空消息的错误,这对我来说很好,因为我稍后在测试中以其他方式检查它。所有不推荐的:
$this->setExpectedException('Exception'); // complained about empty message.
$this->setExpectedExceptionMessage('Message'); // generated weird errors
I try failed.
setExpectedException
告诉PHPUnit期待一个具有给定类名的异常,但是您给了它异常的消息。正如你提到的,即使在那个版本的PHPUnit中,它也已经被弃用了。
PHPUnit 5.7的相关文档显示了该版本中未弃用的方法:https://phpunit.de/manual/5.7/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.exceptions
在您的情况下,正确的调用将是expectException('Exception')
或等价的expectException(Exception::class)
expectExceptionMessage
。