Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Anna Filina:
Testing Methods That Make Static Calls
Jan 13, 2016 @ 15:03:40

Anna Filina has posted a quick hint around testing methods that make static methods calls to other parts of your application. Static method calls are notoriously difficult to test, especially with PHPUnit.

I had trouble testing a particularly painful codebase. It had static calls and implicit dependencies all over the place, to name just a few problems.

One of the things that it often did was to call static methods that would increment counters in the database and cache stuff. Example: Record::incrementViews() It was making things difficult. To avoid messing with the original codebase too much, I came up with this quick and dirty way to ignore those dependencies.

Her solution makes use of a mockStaticDependency method that then turns around and redefines the class in question (like her "Record" above) with a __callStatic through an eval. She points out that usually using eval is "evil" but in this case it made testing the functionality much simpler when no feedback was needed from the static method. In the comments on the post, someone also makes a recommendation of the Patchwork library for PHP that allows for "monkey patching" and modifying classes/functionality to redefine functions and methods in a similar way.

tagged: unittest method static call monkeypatch eval callstatic example

Link: http://afilina.com/testing-methods-that-make-static-calls/

Till Klampaeckel's Blog:
Monkey patching in PHP
Jun 23, 2010 @ 15:31:09

In a new post to his blog today Till Klampaeckel takes a look at monkey patching in PHP - a way to replace functions at runtime.

I haven't really had the chance or time to play with PHP 5.3 until recently when Ubuntu 10.04 upgraded my local installations and kind of forced me to dive into it a little. And I'm also probably the last person on the planet to notice, but namespaces in PHP 5.3 allow you to monkey-patch core PHP code. [...] One of the more common applications is stubbing (or mocking) code in unit tests.

He includes a code sample showing how you can use a simple namespace hack to call a function from another namespace named the same as an internal one - in this case strlen.

tagged: monkeypatch namespace runkit

Link:


Trending Topics: