PHPUnit 测试函数,通过引用传递值和返回值

标签 php unit-testing phpunit

大家好,我需要测试一段调用另一个类的函数的代码 我现在不能编辑 .

我只需要测试它,但问题是这个函数有一个通过引用传递的值和一个返回值,所以我不知道如何模拟它。

这是列类的功能:

    public function functionWithValuePassedByReference(&$matches = null)
    {
        $regex = 'my regex';

        return ($matches === null) ? preg_match($regex, $this->field) : preg_match($regex, $this->field, $matches);
    }

这是调用的地方和我需要模拟的地方:
    $matches = [];
    if ($column->functionWithValuePassedByReference($matches)) {
        if (strtolower($matches['parameters']) == 'distinct') {
            //my code
        }
    }

所以我试过了
   $this->columnMock = $this->createMock(Column::class);
   $this->columnMock
        ->method('functionWithValuePassedByReference')
        ->willReturn(true);

如果我这样做返回错误索引 parameters显然不存在所以我试过这个:
   $this->columnMock = $this->createMock(Column::class);
   $this->columnMock
        ->method('functionWithValuePassedByReference')
        ->with([])
        ->willReturn(true);

但是同样的错误,我该如何模拟该功能?

谢谢

最佳答案

您可以使用 ->willReturnCallback()修改参数并返回一个值。所以你的模拟会变成这样:

$this->columnMock
        ->method('functionWithValuePassedByReference')
        ->with([])
        ->willReturnCallback(function(&$matches) {
           $matches = 'foo';
           return True;
         });

为了使其工作,您需要在构建模拟时关闭克隆模拟的参数。所以你的模拟对象会像这样构建
$this->columnMock = $this->getMockBuilder('Column')
      ->setMethods(['functionWithValuePassedByReference'])
      ->disableArgumentCloning()
      ->getMock();

顺便说一句,这真的是代码味道。我意识到你说你不能改变你正在 mock 的代码。但是对于查看此问题的其他人来说,这样做会在您的代码中造成副作用,并且可能会导致修复错误非常令人沮丧。

关于PHPUnit 测试函数,通过引用传递值和返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44517756/

相关文章:

php - 什么是新静态?

php - 每个客户端请求都是该类的一个新实例?

python - 如何在 Python 中生成动态(参数化)单元测试?

java - Selenium 项目的单元测试

json - 嵌套数组上的 Laravel AssertJsonCount

php - 新闻 | Woocommerce 自定义注册表格

unit-testing - 您是否遇到过 TDD 增加开发时间的情况?

php - 让 PHPUnit 忽略一些东西?

php - 如何在 Laravel 中配置并行测试数据库?

javascript - 我想在 javascript 语法中包含 php 语法