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