小编del*_*ala的帖子

测试使用PHPUnit触发错误的方法的返回值

这个问题特定于使用PHPUnit.

PHPUnit自动将php错误转换为异常.有没有办法测试碰巧触发php错误的方法的返回值(内置错误或用户生成的错误通过trigger_error)?

要测试的代码示例:

function load_file ($file)
{
    if (! file_exists($file)) {
        trigger_error("file {$file} does not exist", E_USER_WARNING);
        return false;
    }
    return file_get_contents($file);
}
Run Code Online (Sandbox Code Playgroud)

这是我想写的测试类型:

public function testLoadFile ()
{
    $this->assertFalse(load_file('/some/non-existent/file'));
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是触发的错误导致我的单元测试失败(应该如此).但是如果我试图捕获它,或者设置一个预期的异常,那么在触发错误之后的任何代码都不会执行,所以我无法测试该方法的返回值.

此示例不起作用:

public function testLoadFile ()
{
    $this->setExpectedException('Exception');
    $result = load_file('/some/non-existent/file');

    // code after this point never gets executed

    $this->assertFalse($result);
}
Run Code Online (Sandbox Code Playgroud)

有什么想法我能做到这一点吗?

php phpunit unit-testing exception

12
推荐指数
2
解决办法
9164
查看次数

你应该在调用preg_match之前初始化$ matches吗?

preg_match接受$matches参数作为参考.我见过的所有例子都没有在它作为参数传递之前初始化它.像这样:

preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Run Code Online (Sandbox Code Playgroud)

这不容易出错吗?如果$matches已包含值,该怎么办?我认为应该在将它作为arg传递之前初始化为空数组.像这样:

$matches = array();
preg_match($somePattern, $someSubject, $matches);
print_r($matches);
Run Code Online (Sandbox Code Playgroud)

我只是偏执狂吗?

php regex

6
推荐指数
1
解决办法
331
查看次数

标签 统计

php ×2

exception ×1

phpunit ×1

regex ×1

unit-testing ×1