PHPUnit 和调用时引用传递

Wil*_*son 5 phpunit pass-by-reference

我正在编写一个单元测试,但遇到了一个恼人的问题...假设我正在测试以下功能:

public function functionToTest(array &$data, parameter2)
{
    // perform some action on the array that is being passed in by reference
}
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试在单元测试中调用此函数时,我会执行以下操作:

public function testMyFunction()
{
    $data = array('key1' => 'val1');

    $mockOfClass = $this->getMockBuilder('ClassName')
        ->disableOriginalConstructor()
        ->setMethods(array('method1', 'method2')) // My function to test is NOT in this list 
        ->getMock();

    $this->mockOfClass->functionToTest($data, true);

    // Perform assertions here
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下错误消息:

ClassName::addNewFriendsToProfile() 的参数 1 预期为引用,给定值

这对我来说似乎很奇怪。首先,我只是通过引用传递一个数组,所以它应该不会有问题。其次,为什么是参数1?不是说参数为0吗?然后,我尝试将调用更改为以下内容:

$this->mockOfClass->functionToTest(&$data, true);
Run Code Online (Sandbox Code Playgroud)

进行此更改后,效果很好。不幸的是,它还会产生以下警告:

调用时按引用传递已在第 xxx 行的 /PathToFile 中弃用

我在运行实际代码时没有遇到此错误。它仅在单元测试中抛出此错误。另外,我需要使用模拟,因为我正在模拟的类中有方法;所以我不能简单地创建该类的新实例并调用正在测试的方法。有什么办法可以解决这个问题吗?

Wil*_*son 3

事实证明,PHPUnit 克隆了传入的每个参数(感谢 Tim Lytle 向我指出此来源:在 PHPUnit 中模拟时在回调中按引用传递)。如果在单元测试中调用时传入数组时没有引用,这就是导致错误的原因。幸运的是,解决方案很简单。我没有按引用传递数组,而是按值传递数组并返回该数组。

前:

public function someFunction(array &$myArray)
{
    $myArray[] = 'new val';
}
Run Code Online (Sandbox Code Playgroud)

后:

public function someFunction(array $myArray)
{
    $myArray[] = 'new val';

    return $myArray;
}
Run Code Online (Sandbox Code Playgroud)