As an addition, I wanted to attach expects() calls to my mocked object, and then call the constructor. In PHPUnit 3.7.14, the object that is returned when disableOriginalConstructor() called is literally an object.
// Use a trick to create a new object of a class // without invoking its constructor. $object = unserialize( sprintf('O:%d:"%s":0:{}', strlen($className), $className)
Unfortunately, in PHP 5.4 there is a new parameter that they do not use:
ReflectionClass :: newInstanceWithoutConstructor
Since this was not available, I had to manually display the class and then call the constructor.
$mock = $this->getMockBuilder('class_name') ->disableOriginalConstructor() ->getMock(); $mock->expect($this->once()) ->method('functionCallFromConstructor') ->with($this->equalTo('someValue')); $reflectedClass = new ReflectionClass('class_name'); $constructor = $reflectedClass->getConstructor(); $constructor->invoke($mock);
Note that if functionCallFromConstruct is protected , you need to use setMethods() to make the protected method mock. Example:
$mock->setMethods(array('functionCallFromConstructor'));
setMethods() must be called before expect() called. Personally, I bind this through disableOriginalConstructor() , but before getMock() .
Steve Tauber Mar 08 '13 at 2:21 2013-03-08 02:21
source share