如何使用 PHPUnit 处理失败的 PHP 断言?
我的代码中有一个断言。类似于:
assert('is_string($var)');
如果我为 PHPUnit 编写一个测试,该测试会导致此断言失败并显示以下消息,警告:assert(): Assertion "is_string($var)" failed in /path/to/file.php on line # ##
而且,我的测试也失败了。我尝试将 @expectedException PHPUnit_Framework_Error_Warning
添加到文档块 根据文档,但这没有帮助。我需要做什么才能使我的测试预期此断言会失败?
I have an assertion in my code. Something like:
assert('is_string($var)');
If I write a test for PHPUnit that causes this assertion to fail with the message, Warning: assert(): Assertion "is_string($var)" failed in /path/to/file.php on line ###
And, my test also fails. I've tried adding @expectedException PHPUnit_Framework_Error_Warning
to the docblock according to the documentation, but that doesn't help. What do I need to do to make my test expect that this assertion will fail?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来自 php.net/assert:
因此,对于正常的代码逻辑,请使用布尔值或一些预定义的常量。对于异常逻辑,请使用正常的
if
语句,并针对无效输入抛出Exception
。如果您真的热衷于保留断言,您可以定义一个断言回调,它会抛出一个可以在 PHPUnit 中捕获的
Exception
。From php.net/assert:
So for normal code logic, use a boolean or some pre-defined constants. For exceptional logic use normal
if
statements and throw anException
for invalid input.If you are really keen on keeping the asserts, you could define an assert callback which throws an
Exception
you can catch in PHPUnit.仅当测试失败时断言才会失败。
Assertions should only fail when a test fails.