PHPUnit 测试函数,具有通过引用传递的值和返回值 [英] PHPUnit test function with value passed by reference and a returned value

查看:47
本文介绍了PHPUnit 测试函数,具有通过引用传递的值和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hi all I need to test a piece of code that call a function of another class that I can't edit now.

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

I need only to test It but the problem is that this function has a values passed by reference and a value returned, so I don't know how to mock It.

这是列类的功能:

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

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

这是被调用和我需要模拟的地方:

This is the point where is called and where I need to mock:

    $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 显然不存在所以我试过这个:

If I do this return me error that index parameters doesn't exist obviously so I have tried this:

   $this->columnMock = $this->createMock(Column::class);
   $this->columnMock
        ->method('functionWithValuePassedByReference')
        ->with([])
        ->willReturn(true);

但是同样的错误,我该如何模拟该函数?

But same error, how can I mock that function?

谢谢

推荐答案

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

You can use ->willReturnCallback() to modify the argument and also return a value. So your mock would become like this:

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

为了使其工作,您需要在构建模拟时关闭克隆模拟的参数.所以你的模拟对象会像这样构建

In order for this to work, you will need to turn off cloning the mock's arguments when you build the mock. So your mock object would be built like so

$this->columnMock = $this->getMockBuilder('Column')
      ->setMethods(['functionWithValuePassedByReference'])
      ->disableArgumentCloning()
      ->getMock();

顺便说一句,这真的是代码异味.我意识到你说你不能改变你正在嘲笑的代码.但对于关注此问题的其他人来说,这样做会在您的代码中产生副作用,并且可能会导致修复错误非常令人沮丧.

This really is code smell, btw. I realize that you stated that you can't change the code that you are mocking. But for other people looking at this question, doing this is causing side effects in your code and can be a source of very frustrating to fix bugs.

这篇关于PHPUnit 测试函数,具有通过引用传递的值和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆