Creating test doubles in pure PHP
The PHP world is not known for good unit test coverage. It’s mostly a cultural issue, but there is a technical aspect to it as well.
PHPUnit allows you to create mock objects, but that assumes your codebase uses the Depedency Injection pattern. If not, it’s very hard to add unit tests without doing major refactorings, because the language doesn’t support monkey patching (i.e. redefining functions and methods at runtime).
You could install the runkit extension, which allows you to replace everything, including constants. However, that means that anyone who wants to run the tests needs to re-compile their PHP.
Patchwork is a PHP library that makes it possible to redefine user-defined functions and methods at runtime, replicating the functionality of
runkit_function_redefinein pure PHP 5.3 code.
I started using it to create mocks and it’s great, but I had this nagging thought: how the hell does it work?
I set out to figure out what black magic the author uses, only to find that he already wrote a very easy to understand description of the implementation, like any responsible developer would. Neat!
Gems like these are few and far between in the PHP ecosystem, but they do exist.comments powered by Disqus