//ads:
?>
phpunit - mockbuilder - set mock object internal property
PHP Snippet 1:
$a = new A;
$reflection = new ReflectionClass($a);
$reflection_property = $reflection->getProperty('p');
$reflection_property->setAccessible(true);
$reflection_property->setValue($a, 2);
PHP Snippet 2:
$mockA = $this->getMockBuilder('A')
->disableOriginalConstructor()
->getMock();
$mockA->expects($this->any())
->method('blah')
->will($this->throwException(new Exception));
PHP Snippet 3:
/**
* Sets a protected property on a given object via reflection
*
* @param $object - instance in which protected value is being modified
* @param $property - property on instance being modified
* @param $value - new value of the property being modified
*
* @return void
*/
public function setProtectedProperty($object, $property, $value)
{
$reflection = new ReflectionClass($object);
$reflection_property = $reflection->getProperty($property);
$reflection_property->setAccessible(true);
$reflection_property->setValue($object, $value);
}
PHP Snippet 4:
$a = $this->getMockBuilder(A::class)
->disableOriginalConstructor()
->getMock();
$reflection = new ReflectionClass(A::class);
$reflection_property = $reflection->getProperty('p');
$reflection_property->setAccessible(true);
$reflection_property->setValue($a, 2);
PHP Snippet 5:
/**
* Makes any properties (private/protected etc) accessible on a given object via reflection
*
* @param $object - instance in which properties are being modified
* @param array $properties - associative array ['propertyName' => 'propertyValue']
* @return void
* @throws ReflectionException
*/
public function setProperties($object, $properties)
{
$reflection = new ReflectionClass($object);
foreach ($properties as $name => $value) {
$reflection_property = $reflection->getProperty($name);
$reflection_property->setAccessible(true);
$reflection_property->setValue($object, $value);
}
}
PHP Snippet 6:
$mock = $this->createMock(MyClass::class);
$this->setProperties($mock, [
'propname1' => 'valueOfPrivateProp1',
'propname2' => 'valueOfPrivateProp2'
]);
PHP Snippet 7:
public function __construct(BlahClass $blah)
{
$this->protectedProperty = new FooClass($blah);
}