WELCOME TO THE BLOG

Using Prophecy with PHPUnit

We’ve recently been converting all of our PHP unit tests from SimpleTest to PHPUnit. For test doubles/mocks/spies/dummies, we’ve switched to exclusively using Everzet’s outstanding new mocking/stubbing library Prophecy, which PHPUnit 4.5 natively supports.

Prophecy is crazy cool, but you can definitely tell it was written for the magical BDD style that phpspec uses. Using it from within PHPUnit with non-BDD style semantics is a bit awkard and verbose. You have to write a bunch of lines of code just to spin up a quick and dirty test dummy. Say I just want an object that will return `false` for a certain method:

That’s a lot of typing with some weird semantics just to get a simple double.

Also, I found it really difficult to figure out some of the argument matching and spying features of Prophecy. The documentation is OK, but pretty sparse. I could tell that just about everything I wanted to do, I was pretty sure that Prophecy could do, but from reading the README and perusing the source code, I was still having a lot of trouble getting it do what I wanted it to do.

To mitigate these issues, I built a wrapper for using Prophecy within PHPUnit that gives you a terse but expressive layer of syntatic sugar on top of Prophecy called Ezekiel. It also adds simple, well-documented support for most of the basic mocking and stubbing use-cases you’ll encounter in an average test case. It also adds some cool convenience methods and tricks that make mocking/stubbing simpler and faster.

With Ezekiel, you can re-write the example above as:

Or stub simple returns for multiple methods like this:

Ezekiel has a longer syntax that allows you to match arguments and return different values based on arguments matched.

There’s a bunch more it can do as well, including returning the stub object, creating predictions, inspecting invocations, returning arguments by index, returning public properties of the test case. If you’re interested, it’s worth reading the full documentation, which is in the README file on GitHub:

https://github.com/netrivet/ezekiel

It’s definitely simplistic and a bit naive, but that’s the point — it’s not meant to prevent you from ever using prophecy directly, just to give you a shorthand for common scenarios. The readme linked above has installation instructions if you want to give it a spin, or submit an issue or pull request.

Get a $30 rebate when you choose our recommended host, Bluehost