markbaker / spymaster
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, without needing to modify the class using Reflection.
Requires
- php: ^7.0 || ^8.0
Requires (Dev)
- dealerdirect/phpcodesniffer-composer-installer: ^0.7.0
- phpcompatibility/php-compatibility: ^9.0
- phpdocumentor/phpdocumentor: 2.*
- phploc/phploc: ^4.0
- phpmd/phpmd: 2.*
- phpunit/phpunit: ^6.0 || ^7.0 || ^8.0 || ^9.3
- sebastian/phpcpd: ^3.0 || ^4.0 || ^6.0
- squizlabs/php_codesniffer: ^3.4
- yoast/phpunit-polyfills: 1.x-dev
This package is auto-updated.
Last update: 2024-11-23 23:55:52 UTC
README
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.
Requirements
- PHP version 7.0.0 or higher
Installation
Using composer, either
composer require markbaker/spymaster
or add the library to your existing composer.json file, and let composer's own autoloader work its magic.
Or you can download the files from github, and include the bootstrap.php file to enable the SpyMaster autoloader
Usage
There are a few examples of use in the /examples
folder.
// 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.
To execute private or protected methods inside an object, you can use a Manipulator
.
// 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