PHPackages                             unit-testing/class-spy - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. unit-testing/class-spy

ActiveLibrary[Testing &amp; Quality](/categories/testing)

unit-testing/class-spy
======================

a simple trait that aids in unit testing protected class methods

v1.0.0(11y ago)03.9kMITPHPPHP &gt;=5.4.0

Since Feb 27Pushed 11y ago1 watchersCompare

[ Source](https://github.com/unit-testing/class-spy)[ Packagist](https://packagist.org/packages/unit-testing/class-spy)[ RSS](/packages/unit-testing-class-spy/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (2)Versions (2)Used By (0)

UnitTesting\\ClassSpy
=====================

[](#unittestingclassspy)

In some cases, you may want to mock a class's methods without using testing facility like . This trait will let you do that.

Installation
------------

[](#installation)

- `composer require --dev unit-testing/class-spy:dev-master`
- or in `require-dev` block of `composer.json`, add `"unit-testing/class-spy": "dev-master"` and then run `composer update`

Usage
-----

[](#usage)

In your phpunit test, you'll create a stub of your class under test. In that stub definition, add `use \UnitTesting\ClassSpy\WatchableTrait;`. Your stub will be extended with the following methods:

- `trackMethodCall`: For any method you want to test on the stub, you can create (or override its parent) method by calling `return $this->trackMethodCall();` from within the method.
- `getAllMethodCalls`: Returns an array of all the arguments passed to all tracked methods. The array has a list of method names as keys and an array of arguments passed to the method as the value.
- `getMethodCalls($method, $index = null)`: Pass the method name to get the arguments passed to it. Optionally add an index (where 1 = the first call) to get the arguments for a specific call if the method was called more than once. If the argument was never called, or was not called less times than the index provided, it will return null.
- `getLastMethodCall($method)`: Get the last set of arguments for a particular method.
- `setMethodResult($method, $result)`: Fake a specific result to be passed back from your tracked method. If the `$result` parameter is an instance `Closure`, the Closure will be executed with the actual parameters and its result will be returned.

All of the above have their equivalents for static class methods: `trackStaticMethodCall`, `getAllStaticMethodCalls`, `getStaticMethodCalls`, `getLastStaticMethodCall`, `setStaticMethodResult`.

Example
-------

[](#example)

```
