Trying to spy on invocations with PHPUnit seems to normally involve either writing your own spy class:
1 2 3 4 5 6 |
|
or trying to use execution checks on mock objects to determine that things were called with the right arguments:
1 2 3 4 |
|
What A Pain!
What if you want to check the arguments going in to the last call? Well you can use at()
:
1
|
|
… better hope we never add any other calls!
What if we don’t know the exact parameter that it’s being called with and want to check it with something more complex? Well if you dig really hard in the manual you’ll find there’s a whole bunch of assertions that let you feed in crazier stuff like:
1 2 3 4 |
|
So that’s pretty cool, if you happen to like really obscure features that are impossible to remember.
Surely there’s a better way? Think of the children!
What if you could just ask for all the invocations and test that they were right in that language you’re already using for all your production logic? Wouldn’t that be just dandy!
Turns out you can, but it’s hiding - and I don’t mean it’s hiding in a “you will find this if you read the manual” kind of way, I mean it’s hiding in the source code, where everyone totally looks first for easy examples right?
All you have to do is store the result of $this->any()
and you can use it as a spy:
1 2 |
|
(I’ve got to wonder if documenting those extra 7 characters might be the colloquial straw that breaks the PHPUnit manual’s back.)
Now that you have a spy, you can just do normal stuff that calls it, then use normal PHP logic (I had to laugh when I wrote “normal PHP logic”) to confirm it’s right:
1 2 3 |
|
An Example You Say?
As a concrete example, lets ensure the NSA is spying on its citizens just the right amount.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
and when we run the tests we can see that even PHPUnit knows the NSA has crossed the line:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|