gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 07:45:15 25 4
gpt4 key购买 nike

我的代码中有一个断言。像这样的东西:

assert('is_string($var)');

如果我为 PHPUnit 编写的测试导致此断言失败并显示消息,警告:assert():Assertion "is_string($var)"failed in/path/to/file.php on line # ##

而且,我的测试也失败了。我尝试将 @expectedException PHPUnit_Framework_Error_Warning 添加到文档 block according to the documentation ,但这无济于事。我需要做什么才能让我的测试预期此断言会失败?

最佳答案

来自 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.

因此对于正常的代码逻辑,使用 bool 值或一些预定义的常量。对于异常逻辑,使用普通的 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');
});

关于php - 如何使用 PHPUnit 处理失败的 PHP 断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7488004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com