SpyMaster - Create "Spies" to access the protected and private properties of a class being tested
SpyMaster is a small library, for use in testing, that allows access to verify the values of protected and private properties in a class that is being tested, or execution of protected or private methods, without needing to modify the class using Reflection., (*1)
, (*2)
Requirements
- PHP version 7.0.0 or higher
Installation
Using composer, either, (*3)
composer require markbaker/spymaster
or add the library to your existing composer.json file, and let composer's own autoloader work its magic., (*4)
Or you can download the files from github, and include the bootstrap.php file to enable the SpyMaster autoloader, (*5)
Usage
There are a few examples of use in the /examples
folder., (*6)
// Instantiate your object
$myObject = new myObject();
// Infiltrate a read-only Spy that can view the properties of $myObject
$spy = (new SpyMaster\SpyMaster($myObject))
->infiltrate();
// Access the $value property of $myObject
// Any property of $myObject can be accessed, whether it is public, protected or private
echo $spy->value;
// Instantiate your object
$myObject = new myObject();
// Infiltrate a read-write spy that can both read and modify the properties of $myObject
$spy = (new SpyMaster\SpyMaster($myObject))
->infiltrate(SpyMaster\SpyMaster::SPY_READ_WRITE);
// Access the $value property of $myObject
// Any property of $myObject can be accessed, whether it is public, protected or private
echo $spy->value;
// A Read-Write Spy also allows you to set new values for those properties
$spy->value += 1000;
echo $spy->value;
Spies cannot unset properties, nor can they access properties that are created dynamically after the Spy is infiltrated., (*7)
To execute private or protected methods inside an object, you can use a Manipulator
., (*8)
// Instantiate your object
$myObject = new myObject();
// Create a Manipulator
$Manipulator = new Manipulator();
// Call the Manipulator's execute() method, passing in the object and name of the method to execute, together with any arguments
$result = $Manipulator->execute($myObject, 'add', 3, 5);
// This example would execute the add() method of the myObject instance with arguments 3 and 5
License
SpyMaster is published under the MIT license, (*9)