Skip to content

Instantly share code, notes, and snippets.

@rodaine rodaine/bar.php
Last active Aug 29, 2015

Embed
What would you like to do?
How to mock a protected property on an object (assume for class Baz, Baz#foo uses Baz::$bar which needs to be mocked)
<?php
class Bar
{
public function getSomething()
{
return 'something';
}
}
<?php
class Baz
{
protected $bar;
public function getBar()
{
if (!$this->bar) {
$this->bar = new Bar();
}
return $this->bar;
}
public function setBar(Bar $bar)
{
$this->bar = $bar;
return $this;
}
public function foo()
{
return $this->getBar()->getSomething();
}
}
<?php
//via a getter method on Baz
function testFoo()
{
$barMock = $this->getMock('Bar');
$barMock->expects($this->once())->method('getSomething')->will($this->returnValue('something'));
$baz = $this->getMockBuilder('Baz')->setMethods(array('getBar'))->getMock();
$baz->expects($this->once())->method('getBar')->will($this->returnValue($barMock));
$baz->foo();
}
<?php
//via reflection
function testFoo()
{
$barMock = $this->getMock('Bar');
$barMock->expects($this->once())->method('getSomething')->will($this->returnValue('something'));
$baz = new Baz();
$ref = new ReflectionClass($baz);
$barRef = $ref->getProperty('bar');
$barRef->setAccessible(true);
$barRef->setValue($baz, $barMock);
$baz->foo();
}
<?php
//via a setter method on Baz
function testFoo()
{
$barMock = $this->getMock('Bar');
$barMock->expects($this->once())->method('getSomething')->will($this->returnValue('something'));
$baz = new Baz();
$baz->setBar($barMock);
$baz->foo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.