Blame | Last modification | View Log | Download
# Prophecy[](https://packagist.org/packages/phpspec/prophecy)[](https://travis-ci.org/phpspec/prophecy)Prophecy is a highly opinionated yet very powerful and flexible PHP object mockingframework. Though initially it was created to fulfil phpspec2 needs, it is flexibleenough to be used inside any testing framework out there with minimal effort.## A simple example```php<?phpclass UserTest extends PHPUnit_Framework_TestCase{private $prophet;public function testPasswordHashing(){$hasher = $this->prophet->prophesize('App\Security\Hasher');$user = new App\Entity\User($hasher->reveal());$hasher->generateHash($user, 'qwerty')->willReturn('hashed_pass');$user->setPassword('qwerty');$this->assertEquals('hashed_pass', $user->getPassword());}protected function setup(){$this->prophet = new \Prophecy\Prophet;}protected function tearDown(){$this->prophet->checkPredictions();}}```## Installation### PrerequisitesProphecy requires PHP 5.3.3 or greater.### Setup through composerFirst, add Prophecy to the list of dependencies inside your `composer.json`:```json{"require-dev": {"phpspec/prophecy": "~1.0"}}```Then simply install it with composer:```bash$> composer install --prefer-dist```You can read more about Composer on its [official webpage](http://getcomposer.org).## How to use itFirst of all, in Prophecy every word has a logical meaning, even the name of the libraryitself (Prophecy). When you start feeling that, you'll become very fluid with thistool.For example, Prophecy has been named that way because it concentrates on describing the futurebehavior of objects with very limited knowledge about them. But as with any other prophecy,those object prophecies can't create themselves - there should be a Prophet:```php$prophet = new Prophecy\Prophet;```The Prophet creates prophecies by *prophesizing* them:```php$prophecy = $prophet->prophesize();```The result of the `prophesize()` method call is a new object of class `ObjectProphecy`. Yes,that's your specific object prophecy, which describes how your object would behavein the near future. But first, you need to specify which object you're talking about,right?```php$prophecy->willExtend('stdClass');$prophecy->willImplement('SessionHandlerInterface');```There are 2 interesting calls - `willExtend` and `willImplement`. The first one tellsobject prophecy that our object should extend specific class, the second one says thatit should implement some interface. Obviously, objects in PHP can implement multipleinterfaces, but extend only one parent class.### DummiesOk, now we have our object prophecy. What can we do with it? First of all, we can getour object *dummy* by revealing its prophecy:```php$dummy = $prophecy->reveal();```The `$dummy` variable now holds a special dummy object. Dummy objects are objects that extendand/or implement preset classes/interfaces by overriding all their public methods. The keypoint about dummies is that they do not hold any logic - they just do nothing. Any methodof the dummy will always return `null` and the dummy will never throw any exceptions.Dummy is your friend if you don't care about the actual behavior of this double and just needa token object to satisfy a method typehint.You need to understand one thing - a dummy is not a prophecy. Your object prophecy is stillassigned to `$prophecy` variable and in order to manipulate with your expectations, youshould work with it. `$dummy` is a dummy - a simple php object that tries to fulfil yourprophecy.### StubsOk, now we know how to create basic prophecies and reveal dummies from them. That'sawesome if we don't care about our _doubles_ (objects that reflect originals)interactions. If we do, we need to use *stubs* or *mocks*.A stub is an object double, which doesn't have any expectations about the object behavior,but when put in specific environment, behaves in specific way. Ok, I know, it's cryptic,but bear with me for a minute. Simply put, a stub is a dummy, which depending on the calledmethod signature does different things (has logic). To create stubs in Prophecy:```php$prophecy->read('123')->willReturn('value');```Oh wow. We've just made an arbitrary call on the object prophecy? Yes, we did. And thiscall returned us a new object instance of class `MethodProphecy`. Yep, that's a specificmethod with arguments prophecy. Method prophecies give you the ability to create methodpromises or predictions. We'll talk about method predictions later in the _Mocks_ section.#### PromisesPromises are logical blocks, that represent your fictional methods in prophecy termsand they are handled by the `MethodProphecy::will(PromiseInterface $promise)` method.As a matter of fact, the call that we made earlier (`willReturn('value')`) is a simpleshortcut to:```php$prophecy->read('123')->will(new Prophecy\Promise\ReturnPromise(array('value')));```This promise will cause any call to our double's `read()` method with exactly oneargument - `'123'` to always return `'value'`. But that's only for thispromise, there's plenty others you can use:- `ReturnPromise` or `->willReturn(1)` - returns a value from a method call- `ReturnArgumentPromise` or `->willReturnArgument($index)` - returns the nth method argument from call- `ThrowPromise` or `->willThrow($exception)` - causes the method to throw specific exception- `CallbackPromise` or `->will($callback)` - gives you a quick way to define your own custom logicKeep in mind, that you can always add even more promises by implementing`Prophecy\Promise\PromiseInterface`.#### Method prophecies idempotencyProphecy enforces same method prophecies and, as a consequence, same promises andpredictions for the same method calls with the same arguments. This means:```php$methodProphecy1 = $prophecy->read('123');$methodProphecy2 = $prophecy->read('123');$methodProphecy3 = $prophecy->read('321');$methodProphecy1 === $methodProphecy2;$methodProphecy1 !== $methodProphecy3;```That's interesting, right? Now you might ask me how would you define more complexbehaviors where some method call changes behavior of others. In PHPUnit or Mockeryyou do that by predicting how many times your method will be called. In Prophecy,you'll use promises for that:```php$user->getName()->willReturn(null);// For PHP 5.4$user->setName('everzet')->will(function () {$this->getName()->willReturn('everzet');});// For PHP 5.3$user->setName('everzet')->will(function ($args, $user) {$user->getName()->willReturn('everzet');});// Or$user->setName('everzet')->will(function ($args) use ($user) {$user->getName()->willReturn('everzet');});```And now it doesn't matter how many times or in which order your methods are called.What matters is their behaviors and how well you faked it.#### Arguments wildcardingThe previous example is awesome (at least I hope it is for you), but that's notoptimal enough. We hardcoded `'everzet'` in our expectation. Isn't there a betterway? In fact there is, but it involves understanding what this `'everzet'`actually is.You see, even if method arguments used during method prophecy creation looklike simple method arguments, in reality they are not. They are argument tokenwildcards. As a matter of fact, `->setName('everzet')` looks like a simple call justbecause Prophecy automatically transforms it under the hood into:```php$user->setName(new Prophecy\Argument\Token\ExactValueToken('everzet'));```Those argument tokens are simple PHP classes, that implement`Prophecy\Argument\Token\TokenInterface` and tell Prophecy how to compare real argumentswith your expectations. And yes, those classnames are damn big. That's why there's ashortcut class `Prophecy\Argument`, which you can use to create tokens like that:```phpuse Prophecy\Argument;$user->setName(Argument::exact('everzet'));````ExactValueToken` is not very useful in our case as it forced us to hardcode the username.That's why Prophecy comes bundled with a bunch of other tokens:- `IdenticalValueToken` or `Argument::is($value)` - checks that the argument is identical to a specific value- `ExactValueToken` or `Argument::exact($value)` - checks that the argument matches a specific value- `TypeToken` or `Argument::type($typeOrClass)` - checks that the argument matches a specific type orclassname- `ObjectStateToken` or `Argument::which($method, $value)` - checks that the argument method returnsa specific value- `CallbackToken` or `Argument::that(callback)` - checks that the argument matches a custom callback- `AnyValueToken` or `Argument::any()` - matches any argument- `AnyValuesToken` or `Argument::cetera()` - matches any arguments to the rest of the signature- `StringContainsToken` or `Argument::containingString($value)` - checks that the argument contains a specific string valueAnd you can add even more by implementing `TokenInterface` with your own custom classes.So, let's refactor our initial `{set,get}Name()` logic with argument tokens:```phpuse Prophecy\Argument;$user->getName()->willReturn(null);// For PHP 5.4$user->setName(Argument::type('string'))->will(function ($args) {$this->getName()->willReturn($args[0]);});// For PHP 5.3$user->setName(Argument::type('string'))->will(function ($args, $user) {$user->getName()->willReturn($args[0]);});// Or$user->setName(Argument::type('string'))->will(function ($args) use ($user) {$user->getName()->willReturn($args[0]);});```That's it. Now our `{set,get}Name()` prophecy will work with any string argument provided to it.We've just described how our stub object should behave, even though the original object could haveno behavior whatsoever.One last bit about arguments now. You might ask, what happens in case of:```phpuse Prophecy\Argument;$user->getName()->willReturn(null);// For PHP 5.4$user->setName(Argument::type('string'))->will(function ($args) {$this->getName()->willReturn($args[0]);});// For PHP 5.3$user->setName(Argument::type('string'))->will(function ($args, $user) {$user->getName()->willReturn($args[0]);});// Or$user->setName(Argument::type('string'))->will(function ($args) use ($user) {$user->getName()->willReturn($args[0]);});$user->setName(Argument::any())->will(function () {});```Nothing. Your stub will continue behaving the way it did before. That's because of howarguments wildcarding works. Every argument token type has a different score level, whichwildcard then uses to calculate the final arguments match score and use the method prophecypromise that has the highest score. In this case, `Argument::type()` in case of successscores `5` and `Argument::any()` scores `3`. So the type token wins, as does the first`setName()` method prophecy and its promise. The simple rule of thumb - more precise tokenalways wins.#### Getting stub objectsOk, now we know how to define our prophecy method promises, let's get our stub fromit:```php$stub = $prophecy->reveal();```As you might see, the only difference between how we get dummies and stubs is that withstubs we describe every object conversation instead of just agreeing with `null` returns(object being *dummy*). As a matter of fact, after you define your first promise(method call), Prophecy will force you to define all the communications - it throwsthe `UnexpectedCallException` for any call you didn't describe with object prophecy beforecalling it on a stub.### MocksNow we know how to define doubles without behavior (dummies) and doubles with behavior, butno expectations (stubs). What's left is doubles for which we have some expectations. Theseare called mocks and in Prophecy they look almost exactly the same as stubs, except thatthey define *predictions* instead of *promises* on method prophecies:```php$entityManager->flush()->shouldBeCalled();```#### PredictionsThe `shouldBeCalled()` method here assigns `CallPrediction` to our method prophecy.Predictions are a delayed behavior check for your prophecies. You see, during the entire lifetimeof your doubles, Prophecy records every single call you're making against it inside yourcode. After that, Prophecy can use this collected information to check if it matches definedpredictions. You can assign predictions to method prophecies using the`MethodProphecy::should(PredictionInterface $prediction)` method. As a matter of fact,the `shouldBeCalled()` method we used earlier is just a shortcut to:```php$entityManager->flush()->should(new Prophecy\Prediction\CallPrediction());```It checks if your method of interest (that matches both the method name and the arguments wildcard)was called 1 or more times. If the prediction failed then it throws an exception. When does thischeck happen? Whenever you call `checkPredictions()` on the main Prophet object:```php$prophet->checkPredictions();```In PHPUnit, you would want to put this call into the `tearDown()` method. If no predictionsare defined, it would do nothing. So it won't harm to call it after every test.There are plenty more predictions you can play with:- `CallPrediction` or `shouldBeCalled()` - checks that the method has been called 1 or more times- `NoCallsPrediction` or `shouldNotBeCalled()` - checks that the method has not been called- `CallTimesPrediction` or `shouldBeCalledTimes($count)` - checks that the method has been called`$count` times- `CallbackPrediction` or `should($callback)` - checks the method against your own custom callbackOf course, you can always create your own custom prediction any time by implementing`PredictionInterface`.### SpiesThe last bit of awesomeness in Prophecy is out-of-the-box spies support. As I said in the previoussection, Prophecy records every call made during the double's entire lifetime. This meansyou don't need to record predictions in order to check them. You can also do itmanually by using the `MethodProphecy::shouldHave(PredictionInterface $prediction)` method:```php$em = $prophet->prophesize('Doctrine\ORM\EntityManager');$controller->createUser($em->reveal());$em->flush()->shouldHaveBeenCalled();```Such manipulation with doubles is called spying. And with Prophecy it just works.