Function mocking with Patchwork 07

First draft is made for function and static method mocking, time to tackle instance method mocking.

What’s this again?

The idea of a “unified” function, static method and instance method mocking system came to me while working to implement ad hoc adapters to make WordPress TDD development a reality. The low-hanging fruit (seemed like so) of function and static method mocking tool patchwork offers made me fall into the rabbit hole to attempt the development of my own mocking tool. An almighty one possibly.


Really Phpspec is a wonderful tool that makes TDD a design tool but it is not able, and opinionatedly so, to test legacy code not built to good OOP standards.
PHPUnit can mock and stub almost anything but static methods and functions and that, working on WordPress, is a limit.

Target test case

While adapters are the way I prefer when dealing with legacy code complete code overhauls are not a possibility most of the time and I wanted a unified and simple way to “test it all”.
Function mocking and static method mocking are offered by patchwork

// replace someFunction and return 4
FunctionMocker::stub('someFunction', 4);

// spy SomeClass::staticMethod and return null
$spy = FunctionMocker::spy('SomeClass::staticMethod');


// verify the method was called less than 4 times

while instance method mocking is a benefit I’m getting from PHPUnit and its mocking engine

// mock an instance and make sure it's called
// at least 5 times
$mock = FunctionMocker::mock('SomeClass::instanceMethod')->shouldBeCalledTimes('>=5');

$someSut = new SutClass($mock);



I’ll be wrapping up the tool and releasing it soon and take its deep PHPUnit bond into consideration to allow for more flexible usage.