Leftwing
Leftwing

Reputation: 223

Yii & PHPUnit mocking with fluent/mockbuilder gives weird results

Why is this:

 $mock = $this->getMock("EventDispatcher");
 $mock->expects($this->once())->method("fireEvent");

Not the same as:

$mock = $this->getMock("EventDispatcher")->expects($this->once())->method("fireEvent");

Tried both in conjunction with

Yii::app()->setComponent("dispatch",$mock);

First works, the last gives a fatal error:

Fatal error: Cannot use object of type PHPUnit_Framework_MockObject_Builder_InvocationMocker as array in /var/www/frameworks/yii/base/CModule.php on line 438

I'd expect those two things to have the same results, or did I just write this code on a moment of total brainmeltdown?

Upvotes: 1

Views: 754

Answers (1)

nestedforloop
nestedforloop

Reputation: 158

$mock = $this->getMock("EventDispatcher");

This initial call will return the actual mocked object.

$mock->expects($this->once())->method("fireEvent");

This line makes use of the fluent interface provided by PHPUnit to build up the behavior you want from your mock. Here we aren't actually making use of the return type as it's not assigned to any variable, however if we looked at it we would find it is of type PHPUnit_Framework_MockObject_Builder_InvocationMocker. This would allow us to chain additional behaviour such as

$mock->expects($this->once())
     ->method("fireEvent")
     ->with($this->equalTo('expectedParam'))
    ;

Your second example:

$mock = $this->getMock("EventDispatcher")
                 ->expects($this->once())
                 ->method("fireEvent")
    ;

will create the mock in the same manner, however because the methods are chained on a single line there is no way for us to access the mock itself. The behavior when chaining method calls like this is that the return value of the final call becomes the assigned value, but as shown this will be the PHPUnit_Framework_MockObject_Builder_InvocationMocker. The actual mock will returned by the call to getMock() but not the call to method().

Upvotes: 2

Related Questions