如何使 "ReflectionException: Class ..." 错误通过 PHPUnit 5.7
How to make "ReflectionException: Class ..." errors pass PHPUnit 5.7
我的代码中有这个
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 does not exist
所以我基本上是在没有回溯的情况下用一个错误换取另一个错误。
信息:
- 我必须使用这个过时版本的 PHP 单元。
- 这是一个 WordPress 插件,我用我自己的测试构建在 WP 5.6 PHP单元测试上。
- 这在 PHP 7.4.14 上运行,但我希望此错误会在我打算测试的所有其他版本上触发。
- 我读到一些关于
setExpectedException
被弃用的信息,不确定这是否与此有关。
setExpectedException
告诉 PHPUnit 期望异常 具有给定的 class 名称,但您已经给它 消息 的例外。正如您所提到的,即使在那个版本的 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
.
我通过使用解决了它:
$this->expectException('Exception');
它不会抛出有关空消息的错误,这对我来说很好,因为无论如何我都会在稍后的测试中以其他方式检查它。所有已弃用的内容:
$this->setExpectedException('Exception'); // complained about empty message.
$this->setExpectedExceptionMessage('Message'); // generated weird errors
我尝试失败了。
我的代码中有这个
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 does not exist
所以我基本上是在没有回溯的情况下用一个错误换取另一个错误。
信息:
- 我必须使用这个过时版本的 PHP 单元。
- 这是一个 WordPress 插件,我用我自己的测试构建在 WP 5.6 PHP单元测试上。
- 这在 PHP 7.4.14 上运行,但我希望此错误会在我打算测试的所有其他版本上触发。
- 我读到一些关于
setExpectedException
被弃用的信息,不确定这是否与此有关。
setExpectedException
告诉 PHPUnit 期望异常 具有给定的 class 名称,但您已经给它 消息 的例外。正如您所提到的,即使在那个版本的 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
.
我通过使用解决了它:
$this->expectException('Exception');
它不会抛出有关空消息的错误,这对我来说很好,因为无论如何我都会在稍后的测试中以其他方式检查它。所有已弃用的内容:
$this->setExpectedException('Exception'); // complained about empty message.
$this->setExpectedExceptionMessage('Message'); // generated weird errors
我尝试失败了。