Skip to content

Instantly share code, notes, and snippets.

@fchris82
Created July 24, 2018 12:57
Show Gist options
  • Save fchris82/b64d9e8dcd9628688ab96e5ed92ccf8f to your computer and use it in GitHub Desktop.
Save fchris82/b64d9e8dcd9628688ab96e5ed92ccf8f to your computer and use it in GitHub Desktop.
Trait to PHPUnit tests (allow protected things and deepClone)
trait PhpUnitTrait
{
protected function callObjectProtectedMethod($object, $methodName, $args = [])
{
$reflMethod = new \ReflectionMethod(get_class($object), $methodName);
$reflMethod->setAccessible(true);
return $reflMethod->invokeArgs($object, $args);
}
protected function setObjectProtectedAttribute($object, $attributeName, $value)
{
$property = new \ReflectionProperty(get_class($object), $attributeName);
$property->setAccessible(true);
$property->setValue($object, $value);
}
protected function getObjectProtectedAttribute($object, $attributeName)
{
$property = new \ReflectionProperty(get_class($object), $attributeName);
$property->setAccessible(true);
return $property->getValue($object);
}
protected function assertObjectProtectedAttribute($object, $attributeName, $value)
{
$current = $this->getObjectProtectedAttribute($object, $attributeName);
$this->assertEquals($current, $value);
}
protected function assertEntityProperties($entity, $properties = [])
{
foreach ($properties as $key => $value) {
$this->assertObjectProtectedAttribute($entity, $key, $value);
}
}
/**
* The PHP clone don't make real clone. The object's object will reference instead of clone. Use the
* `$this->deepCloneObject($object)` to make real clone.
*
* @param $object
*
* @return mixed
*/
protected function deepCloneObject($object)
{
return unserialize(serialize($object));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment