我想模拟一个类的方法并执行一个回调,它修改作为参数给出的对象(使用PHP 5.3和PHPUnit 3.5.5).
假设我有以下课程:
class A
{
function foobar($object)
{
doSomething();
}
}
Run Code Online (Sandbox Code Playgroud)
这个设置代码:
$mock = $this->getMockBuilder('A')->getMock();
$mock->expects($this->any())->method('foobar')->will(
$this->returnCallback(function($object) {
$object->property = something;
}));
Run Code Online (Sandbox Code Playgroud)
由于某种原因,对象不会被修改.在var_dump荷兰国际集团$object我认为它是正确的对象.是否可以通过值传递对象?如何配置模拟以接收引用?
大家好,我需要测试一段调用另一个我现在无法编辑的类的函数的代码。
我只需要测试它,但问题是这个函数有一个通过引用传递的值和一个返回值,所以我不知道如何模拟它。
这是列类的功能:
public function functionWithValuePassedByReference(&$matches = null)
{
$regex = 'my regex';
return ($matches === null) ? preg_match($regex, $this->field) : preg_match($regex, $this->field, $matches);
}
Run Code Online (Sandbox Code Playgroud)
这是被调用和我需要模拟的地方:
$matches = [];
if ($column->functionWithValuePassedByReference($matches)) {
if (strtolower($matches['parameters']) == 'distinct') {
//my code
}
}
Run Code Online (Sandbox Code Playgroud)
所以我试过了
$this->columnMock = $this->createMock(Column::class);
$this->columnMock
->method('functionWithValuePassedByReference')
->willReturn(true);
Run Code Online (Sandbox Code Playgroud)
如果我这样做会返回错误,索引parameters显然不存在,所以我试过这个:
$this->columnMock = $this->createMock(Column::class);
$this->columnMock
->method('functionWithValuePassedByReference')
->with([])
->willReturn(true);
Run Code Online (Sandbox Code Playgroud)
但是同样的错误,我如何模拟该功能?
谢谢