Modifying objects in returnCallback() of PHPUnit Mocks(在 PHPUnit Mocks 的 returnCallback() 中修改对象)
问题描述
I want to mock a method of a class and execute a callback which modifies the object given as parameter (using PHP 5.3 with PHPUnit 3.5.5).
Let´s say I have the following class:
class A
{
function foobar($object)
{
doSomething();
}
}
And this setup code:
$mock = $this->getMockBuilder('A')->getMock();
$mock->expects($this->any())->method('foobar')->will(
$this->returnCallback(function($object) {
$object->property = something;
}));
For some reason the object does not get modified. On var_dump
ing $object
I see it is the right object. Could it be that the object gets passed by value? How can I configure the mock to receive a reference?
He Alex,
i talked to Sebastian (the phpunit creator) about that problem and yes: The argument gets clone
ed before it is passed to the callback.
From the top of my head i can't offer you any workaround but i choose to answer anyway to at least tell you that you are doing nothing wrong and that this is expected behavior.
To quote Sebastians comment on IRC on why it clones the argument:
It's a long-going debate between me, myself, and users of PHPUnit whether or not this is right ;-)
To have something copy/pasteable:
Assertion 3 in this codesample will fail. (The variable is only changed in the returned object)
<?php
class A
{
function foobar($o)
{
$o->x = mt_rand(5, 100);
}
}
class Test extends PHPUnit_Framework_TestCase
{
public function testFoo()
{
$mock = $this->getMock('A');
$mock->expects($this->any())
->method('foobar')
->will($this->returnCallback(function($o) { $o->x = 2; return $o; }));
$o = new StdClass;
$o->x = 1;
$this->assertEquals(1, $o->x);
$return = $mock->foobar($o);
$this->assertEquals(2, $return->x);
$this->assertEquals(2, $o->x);
}
}
Update:
Starting with PHPUnit 3.7 the cloning can be turned off. See the last argument off:
public function getMock(
$originalClassName,
$methods = array(),
array $arguments = array(),
$mockClassName = '',
$callOriginalConstructor = TRUE,
$callOriginalClone = TRUE,
$callAutoload = TRUE,
$cloneArguments = FALSE
);
It might even be off by default :)
这篇关于在 PHPUnit Mocks 的 returnCallback() 中修改对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 PHPUnit Mocks 的 returnCallback() 中修改对象
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01