如何使用 PHPUnit 处理失败的 PHP 断言?

发布于 2024-12-05 16:36:27 字数 478 浏览 1 评论 0原文

我的代码中有一个断言。类似于:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

难如初 2024-12-12 16:36:27

来自 php.net/assert

断言只能用作调试功能。您可以使用它们进行健全性检查,测试应始终为 TRUE 的条件,如果不是,则指示一些编程错误,或者检查是否存在某些功能,例如扩展功能或某些系统限制和功能。

断言不应该用于正常的运行时操作,例如输入参数检查。根据经验,如果未激活断言检查,您的代码应该始终能够正常工作。

因此,对于正常的代码逻辑,请使用布尔值或一些预定义的常量。对于异常逻辑,请使用正常的 if 语句,并针对无效输入抛出 Exception

如果您真的热衷于保留断言,您可以定义一个断言回调,它会抛出一个可以在 PHPUnit 中捕获的Exception

// PHP 5.3 Anonymous function as callback
// code is untested
assert_options(ASSERT_CALLBACK, function($file, $line, $code) {
    throw new Exception('Assert failed in $file on line $line');
});

From php.net/assert:

Assertions should be used as a debugging feature only. You may use them for sanity-checks that test for conditions that should always be TRUE and that indicate some programming errors if not or to check for the presence of certain features like extension functions or certain system limits and features.

Assertions should not be used for normal runtime operations like input parameter checks. As a rule of thumb your code should always be able to work correctly if assertion checking is not activated.

So for normal code logic, use a boolean or some pre-defined constants. For exceptional logic use normal if statements and throw an Exception 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.

// PHP 5.3 Anonymous function as callback
// code is untested
assert_options(ASSERT_CALLBACK, function($file, $line, $code) {
    throw new Exception('Assert failed in $file on line $line');
});
养猫人 2024-12-12 16:36:27

仅当测试失败时断言才会失败。

Assertions should only fail when a test fails.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文