Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

php - Modifying objects in returnCallback() of PHPUnit Mocks

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_dumping $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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

He Alex,

i talked to Sebastian (the phpunit creator) about that problem and yes: The argument gets cloneed 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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...