Skip to content

Instantly share code, notes, and snippets.

@rodaine
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodaine/10306359 to your computer and use it in GitHub Desktop.
Save rodaine/10306359 to your computer and use it in GitHub Desktop.
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