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

标签 php unit-testing phpunit assert assertions

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

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/

相关文章:

php - 将多个表合并为一个表,并添加额外的字段值

javascript - 在 PHP 中向随机用户显示 html 内容

php - 如何制作 PHP 测试套件

php - 传递给 Foo::__construct() 的参数 1 必须是 Psr\Log\LoggerTrait 的实例,给出的 Mock_Trait_LoggerTrait_65811a25_bdddd884 的实例

testing - Laravel 4 Controller 测试 - 太多 $this->call() 后出现 ErrorException - 为什么?

php - 谷歌地图过滤器

php - 如何在 PHP 中使用 Imagick 包装文本,以便将其绘制为多行文本?

android - 在 Android Studio 的单元测试功能中获取 AndroidTestCase 或 InstrumentationTestCase 的上下文

python - 让 `python setup.py test` 语法起作用?

php - 单元测试 Laravel 密码重置电子邮件 - 可邮寄未排队