Created
December 12, 2012 19:05
-
-
Save joelkallman/4270612 to your computer and use it in GitHub Desktop.
Extension of PHPUnit_Framework_TestCase for easy access to objects private/protected properties and methods. This allows you maintain proper visibility for methods and properties within your classes while still being able to test fully.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Eclarian Test Case | |
* | |
* Adds callPrivate() and getPrivateProperty() to be able to test | |
* the full class without having to set everything as public | |
* | |
* @package Eclarian | |
* @copyright Copyright (c) 2012, Eclarian, LLC. | |
* @license MIT | |
* @author Eclarian LLC <hello@eclarian.com> | |
*/ | |
class Eclarian_TestCase extends PHPUnit_Framework_TestCase { | |
/** | |
* Call Private | |
* | |
* @param object | |
* @param string Method to call on object | |
* @param array Arguments to pass to $method | |
* @return mixed Return of $method | |
*/ | |
public function callPrivate($obj, $method, $args = array()) | |
{ | |
$reflection = new ReflectionObject($obj); | |
$m = $reflection->getMethod($method); | |
$m->setAccessible(TRUE); | |
return $m->invokeArgs($obj, $args); | |
} | |
// ----------------------------------------------------------------------------- | |
/** | |
* Get Private Property | |
* | |
* Will return the value of any private or protected property | |
* from the current object. | |
* | |
* @param object | |
* @param string | |
* @return mixed Value of the property | |
*/ | |
public function getPrivateProperty($obj, $property) | |
{ | |
$reflection = new ReflectionObject($obj); | |
$prop = $reflection->getProperty($property); | |
$prop->setAccessible(TRUE); | |
return $prop->getValue($obj); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment