Jason Mace Portfolio

PHP Mock Framework

Back to Portfolio

I needed a light-weight PHP Mock library that would mock classes in-place (as opposed to making a copy, which is how most work). I wasn't able to find one at the time, so I wrote one instead.

The problem was that we had existing code that looked like this:


class A {
    // We want to unit test this method
    public function foo() {
        /* do stuff */
        $b = new B();
        $b->someDangerousMethod();
        /* do stuff */
    }
}

You're probably thinking, you should just refacor your code! And you'd be completely right. But, we had a lot of code like this, and we needed code coverage to ensure behavior wasn't changed by accident. So, while we worked on doing some refactoring, this library came in handy.

Here's an example usage:


Mocktail::generateClassMock('./path/to/SomeClass.php');

//Create and use the class normally
$mock = new SomeClass();

//Set return values
Mocktail::setMethodReturnValues('SomeClass', 'someMethod', array(1,2,3));
$mock->someMethod(); //will return 1
$mock->someMethod(); //will return 2
$mock->someMethod(); //will return 3

//Get the number of times a method was called
Mocktail::getGlobalMethodCount('SomeClass', 'someMethod'); //Will return 3

//Reset the method call counter
Mocktail::resetGlobalMethodCount('SomeClass', 'someMethod'); //reset on method counter
Mocktail::resetAllGlobalCounts('SomeClass');                 //reset all counters

//Spy on a method
function spyFunction($params) { echo 'I was called!'; }
Mocktail::setSpy('SomeClass', 'someMethod', 'spyFunction');
$mock->someMethod(); //will print 'I was called!'

You can, of course, find the whole project on GitHub.