Skip to content

Instantly share code, notes, and snippets.

@kimhogeling
Created December 18, 2017 16:14
Show Gist options
  • Save kimhogeling/964f1ee7f1a1925b9c67e886ca664f9a to your computer and use it in GitHub Desktop.
Save kimhogeling/964f1ee7f1a1925b9c67e886ca664f9a to your computer and use it in GitHub Desktop.
test helper for private methods
<?php
namespace xxx\Tests;
class Helper
{
public static function invokePrivateMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
public static function getPrivateProperty(&$object, $propertyName)
{
$reflection = new \ReflectionClass(get_class($object));
$reflectionProperty = $reflection->getProperty($propertyName);
$reflectionProperty->setAccessible(true);
return $reflectionProperty->getValue($object);
}
public static function setPrivateProperty(&$object, $propertyName, $value)
{
$reflection = new \ReflectionClass(get_class($object));
$reflectionProperty = $reflection->getProperty($propertyName);
$reflectionProperty->setAccessible(true);
$reflectionProperty->setValue($object, $value);
}
}
<?php
namespace xxx\Tests\Unit\yyy;
use xxx\Tests\TestCase;
use xxx\Tests\Helper;
use xxx\SomeClass;
class yyyTest extends TestCase
{
/**
* @test
*/
public function cacheKeyIds()
{
$someInstance = new SomeClass();
$resultOfPrivateMethod = Helper::invokePrivateMethod($someInstance, 'nameOfThePrivateMethod', [
'param1',
'param2'
]);
$this->assertEquals('the expected result', $resultOfPrivateMethod);
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment