Skip to content

Instantly share code, notes, and snippets.

@dsnopek
Last active January 18, 2017 16:54
Show Gist options
  • Save dsnopek/1815e7a676378c68e6765329c8864036 to your computer and use it in GitHub Desktop.
Save dsnopek/1815e7a676378c68e6765329c8864036 to your computer and use it in GitHub Desktop.
<?php
class MyObjectUnitTest extends UnitTestBase {
/**
* Mock object for one of the objects dependencies.
*
* @var \Project\Dependency|\Prophecy\Prophecy\ObjectProphecy
*/
protected $dependency;
/**
* {@inheritdoc}
*/
public function setUp() {
$this->dependency = $this->prophesize(Dependency::class);
}
/**
* Create a new object, optionally with some methods mocked.
*
* @param string[] $mock_methods
* List of method names to mock.
*
* @return \Project\MyObject|\PHPUnit_Framework_MockObject_MockObject
* Mock object wrapping the real object.
*/
protected function createMyObject($mock_methods = []) {
$report_generator = $this->getMockBuilder(Object::class)
->setConstructorArgs([
$this->dependency->reveal(),
])
->setMethods($mock_methods)
->getMock();
return $report_generator;
}
public function testProtectedMethod() {
// Create the object under test, but we're going to mock one of it's internal methods
// so that our test *only* calls the method under test, and any other methods that
// get called are mocked (in this case, there's only one).
$object = $this->createMyObject(['internalMethod']);
$object->method('internalMethod')
->willReturn(['value' => 'test']);
$result = $this->invokeMethod($object, 'protectedMethod', ['argument1']);
$this->assertEqual("expected value", $result);
}
}
<?php
abstract class UnitTestBase extends \PHPUnit_Framework_TestCase {
/**
* Call protected/private method of a class.
*
* @param object &$object
* Instantiated object that we will run method on.
* @param string $methodName
* Method name to call
* @param array $parameters
* Array of parameters to pass into method.
*
* @return mixed
* Method return.
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment